Skip to content Skip to sidebar Skip to footer

Cannot Read Property 'someProperty' Of Undefined In React

I am working on an application where I pass variable values in a Navlink using state from one component to the other and then load those received values in input fields and click o

Solution 1:


 this.state = {id: this.props.location && this.props.location.state && this.props.location.state.id}

Should fix your issue that caused by times that this component called without this context or this line got excuted before location set. (assuming you using withRouter for making location props be exist...)

Anyhow, and not related directly to your issue, it is bad practice to set initial value for state from props at constructor, consider manipulate state through life cycle either don't use state here and refer to props directly


Solution 2:

I would suggest to just use arrow functions for setId and addOrEdit.

addOrEdit = (e) => {
    // ...
}

And just call them:

onChange={this.setId}
onClick={this.addOrEdit}

https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb

Also you are deriving state from prop. It is better to just use the prop directly.

https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html


Post a Comment for "Cannot Read Property 'someProperty' Of Undefined In React"