gpt4 book ai didi

javascript - 为什么在这种情况下我需要 componentWillReceiveProps?

转载 作者:行者123 更新时间:2023-12-02 14:09:41 24 4
gpt4 key购买 nike

我有以下组件代码:

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 中获取新状态,然后将此新状态作为 props 传递给 Comments 组件。我期望当我在 componentWillMountsetState 时,它会负责刷新我的 Comments 组件并传递新的 props,但是,它变成了我需要在我的 Comments 组件中使用此方法:

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

有人可以解释为什么当我设置 paren 的状态后我的父组件没有更新传递给其子组件的 props 吗?

最佳答案

这是因为您正在通过传递的 props 初始化 Comments 组件中的状态。在子组件中初始化在父组件中发生更改的状态不会在子组件中重新运行初始化代码。我希望您的 Comments 组件 getInitialState 方法看起来像这样

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

此方法仅在 Comments 初始化时调用一次,因此当您传递新的 props 时,它不会将注释设置为 Comments 组件中的新注释,除非您使用了componentWillReceiveProps。如果你的 child 的状态与 parent 提供的状态相同,你就不应该在 child 身上建立新的状态。

如果状态仅由 Answer 管理,则删除 Comments 组件中的评论状态,并仅将其用作 Comments 中的 props。

关于javascript - 为什么在这种情况下我需要 componentWillReceiveProps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39734491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com