【问题标题】:Props becoming null after they are passed into react component道具传递到反应组件后变为空
【发布时间】:2017-05-20 16:22:28
【问题描述】:

我在 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 组件的构造函数中,它们为空:

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

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

【问题讨论】:

  • 您是否通过 API 请求异步获取数据?然后你需要在每次props改变componentWillReceiveProps()setState,因为在你初始化组件的时候数据还没有加载。
  • 解决了!非常感谢,将其添加为答案,我将其标记为正确?
  • 当然,很高兴我能帮上忙!

标签: reactjs components


【解决方案1】:

您通过 API 请求异步获取数据,因此在您初始化组件时(在 constructor 内)不会加载数据。而是使用 React 的 componentWillReceiveProps() 来设置组件每次收到 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)
  };  
}

【讨论】:

    猜你喜欢
    • 2017-01-31
    • 2020-08-06
    • 2019-07-29
    • 1970-01-01
    • 2019-08-15
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多