Ahmad Al-kheat Ahmad Al-kheat - 1 year ago 76
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(){
context: this,
method: 'GET',
url: '/answers/' + this.props.answer.id + '/comments',
success: function(data){
this.setState({comments: data});

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

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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download