Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

reactjs - React Uncaught TypeError: cannot read property x of undefined

I have a component that gets data as prop from parent component via react router Link component like this:

<Link to={{pathname: "/cv", state:cvData }}>Next</Link>

And the CV component in that "/cv" path gets that state. But in the JSX of the CV-component, I cannot access data in that state. The code is like this:

const [cvData, setCvData] = useState(props.state)
useEffect(() => {
    setCvData(props.cvData)
    console.log(cvData)
}, [])

The output of that console.log is first undefined and then the data. But even though it logs the right data, the JSX part throws error of 'cannot read property x of undefined'.

question from:https://stackoverflow.com/questions/65871621/react-uncaught-typeerror-cannot-read-property-x-of-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because at some point in the beginning your data is first undefined,you can add a simple check condition before using it,for example:

return(
  <div>
    { cvData && cvData.x ? <div>display your cvData</div> : null }
  </div>
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...