简体   繁体   中英

React/Redux cannot read 'prop' of undefined

I'm having trouble accessing a property of a props object. I can console log the entire object but if I try and console log the property it says the object isn't there.

class SingleCase extends Component {
  componentDidlMount() {
    this.props.getCurrentCase(this.props.location.id);
  }

  render() {
    console.log(this.props.current_case); // This works (Shows the object)
    console.log(this.props.current_case.description); // This fails with current_case is undefined

    return (
      <div>
        <h2>{this.props.current_case.description}</h2>
      </div>
    ); // this won't find the description in undefined
  }
}
export const mapStateToProps = (state) => ({
  current_case: state.cases.current_case,
});
//, { getFullGrievance }
export default connect(mapStateToProps, { getCurrentCase })(SingleCase);

Is it a timing thing? There is no async request, to get the current case the action searches through an already established list and finds the one I need. Is the render getting run before props is set? If so, why can I view the entire props properly but not the one part I need?

In reducr intiail state i think you have just defined current_case:{}....instead try current_case:{description:""}

@karani jaswanth is correct. It have another solution. Use inline condition.

this.props?.current_case?.description

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM