【发布时间】: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