Props becoming null after they are passed into react component

守給你的承諾、 提交于 2019-12-25 08:27:36

问题


I am having a very strange error in React where a component is seeing a couple of the parameters being passed into it as null. Here is the code for the parent component:

  return (
    <div>
      {postUpvoteCount} {postUpvoteId}
      <div className='col-xs-1 col-sm-1 comment-upvote'><Upvote upvoteId={postUpvoteId} upvoteCount={postUpvoteCount} userId={userId} postId={postId} commentId='-1'/></div>
    </div>
  );  

As you can see I check to make sure that the value of postUpvoteCount and postUpvoteId are defined right before passing it into the Upvote component. However when in the constructor for the Upvote component they are null:

  constructor(props){
    super(props);

    console.log(this.props);
    this.state = { 
      upvoteId: this.props.upvoteId,
      upvoteCount: Number(this.props.upvoteCount),
      commentId: this.props.commentId,
      postId: this.props.postId,
      userId: this.props.userId,
      upvoted: Boolean(this.props.upvoteId)
    };  
  }

When I call console.log on the props, I am getting a null for this.props.upvoteCount and this.props.upvoteId. How is this possible?


回答1:


You are getting the data asynchronously with an API request, so it is not loaded in at the time you initialize the component (inside constructor). Instead, use React's componentWillReceiveProps() to set the state every time the component receives props.

componentWillReceiveProps(props) {
  this.setState({
    upvoteId: props.upvoteId,
    upvoteCount: Number(props.upvoteCount),
    commentId: props.commentId,
    postId: props.postId,
    userId: props.userId,
    upvoted: Boolean(props.upvoteId)
  };  
}


来源:https://stackoverflow.com/questions/41496655/props-becoming-null-after-they-are-passed-into-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!