我有以下組件代碼:爲什麼在這種情況下需要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
組件。我期待,當我setState
在componentWillMount
,這將需要刷新我的Comments
成分的護理,並通過新的道具,然而,事實證明,我需要在我Comments
組件此方法:
componentWillReceiveProps: function(newProps){
this.setState({comments: newProps.comments})
},
能有人請解釋爲什麼當我設置paren的狀態後,我的父組件沒有更新傳遞給它的孩子的道具?
*「但是,事實證明,我需要在我的」評論「組件中使用這種方法。」*如果您將道具存儲在似乎是這種情況的狀態中,則只需執行此操作。請參閱https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html,這是我懷疑你正在做的事情。 –
@FelixKling是的,我正在存儲道具狀態,我應該嘗試不? –
是的,如果你不必這樣做,你應該避免這種情況。看鏈接:) –