2016-09-27 72 views
0

我有以下组件代码:为什么在这种情况下需要componentWillReceiveProps?

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

注意我是如何在componentWillMount获取新的状态,然后通过这个新状态的道具到Comments组件。我期待,当我setStatecomponentWillMount,这将需要刷新我的Comments成分的护理,并通过新的道具,然而,事实证明,我需要在我Comments组件此方法:

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

能有人请解释为什么当我设置paren的状态后,我的父组件没有更新传递给它的孩子的道具?

+0

*“但是,事实证明,我需要在我的”评论“组件中使用这种方法。”*如果您将道具存储在似乎是这种情况的状态中,则只需执行此操作。请参阅https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html,这是我怀疑你正在做的事情。 –

+0

@FelixKling是的,我正在存储道具状态,我应该尝试不? –

+1

是的,如果你不必这样做,你应该避免这种情况。看链接:) –

回答

1

这是因为您正在从传递的道具中初始化Comments组件中的状态。初始化在父组件中被更改的子组件中的状态不会重新运行子组件中的初始化代码。我期待你的Comments组件getInitialState方法看起来像这样

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

此方法仅调用一次,当Comments当你通过新道具被初始化的话,它不会设置意见换新的除非您使用componentWillReceiveProps,否则请使用Comments组件。如果您的孩子与父母所提供的相同,则不应该为您的孩子建立新的状态。

如果状态仅由Answer管理,则删除Comments组件中的注释状态,并仅将其作为Comments中的道具使用。

相关问题