问题
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