我有以下组件代码:为什么在这种情况下需要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是的,我正在存储道具状态,我应该尝试不? –
是的,如果你不必这样做,你应该避免这种情况。看链接:) –