【发布时间】:2017-02-13 17:44:24
【问题描述】:
我试图让子组件知道它应该在父组件中的 prop 更改后更新其状态。
没有需要在两者之间共享的状态。唯一需要做的是父母应该以某种方式让孩子知道它需要更新其状态(字面意思是使用它已经拥有的信息单独调用setState)。
到目前为止,我只能通过componentWillReceiveProps 以“React”方式进行操作,并发送一些任意道具,例如数字,让孩子知道它应该调用该函数来设置状态。
另一种方法是使用信号让孩子知道,但对于这种情况,这似乎有点过头了。
总之:
- 父母需要让孩子知道它应该调用一个函数
- 该函数将更新孩子的状态(
setState) - 孩子不需要从父母那里收到任何信息
谁能帮我找出最好的方法来做到这一点?
正如您在 sn-p 中看到的,或多或少是这种情况。我想知道当 Parent 道具发生变化时让 Child 组件调用 _updateState 函数的最佳方法(现在在 sn-p 中不会发生)。
//Imagine this is the redux-container that passes the store state to the parent.
class ParentWrapper extends React.Component {
constructor(){
super();
this.state = {status: 'normal'};
}
//This would be an action to the reducer that would update the store state
_updateStatus(){
this.setState({status: 'updated'});
}
render(){
return (
<div>
<button onClick={this._updateStatus.bind(this)}>Click me</button>
<Parent status={this.state.status} />
</div>
);
}
}
class Parent extends React.Component {
render(){
return (
<div>
<Child />
</div>
);
}
}
Parent.propTypes = {
status: React.PropTypes.string
};
Parent.defaultProps = {
status: 'normal'
};
class Child extends React.Component {
constructor(){
super();
this.state = { test: 1 };
}
_updateState(){
this.setState({test: this.state.test + 1});
}
render(){
return (
<div>Child: {this.state.test}</div>
);
}
}
ReactDOM.render(<ParentWrapper />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="container"></div>
编辑:添加了 sn-p。
【问题讨论】:
-
如果您的孩子没有收到任何信息,它如何知道何时设置新状态?顺便说一句
componentWillReceiveProps是你所需要的 -
@Maxx 我知道我可以使用
componentWillReceiveProps。问题是我只发送道具,因为我需要孩子调用一个函数。我实际上并没有给它任何新的道具。这就是为什么我想知道是否有更好的做法。 -
@Robin_f 看起来不像反应方式。如果你有这种情况,那么你可能做错了什么。你能举例说明你为什么需要这个吗?
-
@Maxx 我有一个解耦组件,用于包含自己状态的不同库中。在父级更改其道具后,我需要它重置自己的状态。
-
@T.J.Crowder 添加了 sn-p。感谢您的提示。
标签: javascript reactjs signals components