Ahmad Al-kheat Ahmad Al-kheat - 2 months ago 7
Javascript Question

Why do I need componentWillReceiveProps in this situation?

I have the following component code :

var Answer = React.createClass({

getInitialState: function(){
return { comments: []}
},

componentWillMount: function(){
$.ajax({
context: this,
method: 'GET',
url: '/answers/' + this.props.answer.id + '/comments',
success: function(data){
this.setState({comments: data});
}
});
},

render: function(){
return (
<div>
<Comments comments={this.state.comments} />
</div>
);
},


Notice how I fetch new state in
componentWillMount
, then pass this new state as props to the
Comments
component. I was expecting that when I
setState
in
componentWillMount
, that would take care of refreshing my
Comments
component and pass the new props, however, it turns out I need this method in my
Comments
component:

componentWillReceiveProps: function(newProps){
this.setState({comments: newProps.comments})
},


Can someone please explain why when my parent component doesn't update the props that are being passed to its child after I set the paren's state?

Answer

It's because you are initializing a state in your Comments component from the passed props. Initializing a state in a child component that gets changed in a parent component won't re-run the initilizaing code in the child. I'm expecting your Comments component getInitialState method to look something like this

getInitialState: function(){
  return { comments: this.props.comments}
},

This method is only called once when Comments is initialized so when you pass new props, it wouldn't set the comments to the new ones in Comments component unless you used componentWillReceiveProps. You shouldn't be making a new state in your child if it's the same as what the parent is providing.

If state is managed only by Answer then delete comments state in your Comments component and use it only as props in Comments.

Comments