2016-09-27 70 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中的道具使用。

相關問題