Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 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 Reply

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>
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...