道具在传递到反应组件后变为空

时间:2017-01-05 23:41:57

标签: reactjs components

我在React中遇到一个非常奇怪的错误,其中一个组件看到一些参数被传递给它为null。以下是父组件的代码:

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

如您所见,我检查以确保postUpvoteCount和postUpvoteId的值在将其传递到Upvote组件之前就已定义。但是,当在Upvote组件的构造函数中,它们为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)
    };  
  }

当我在props上调用console.log时,我得到了this.props.upvoteCount和this.props.upvoteId的null。这怎么可能?

1 个答案:

答案 0 :(得分:2)

您正在使用API​​请求异步获取数据,因此在初始化组件时(constructor内)不会加载它。相反,每次组件接收道具时,使用React的componentWillReceiveProps()来设置状态。

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