让子节点知道它应该在React中更新自己的状态
Letting a child know that it should update its state in React
我想让子组件知道它应该在父组件的prop更改后更新其状态。
两者之间没有需要共享的状态。唯一需要发生的事情是,父进程应该以某种方式让子进程知道它需要更新它的状态(实际上是用它已经拥有的信息自己调用setState
)。
到目前为止,我只能通过"React"的方式通过componentWillReceiveProps
和发送一些任意的道具,如数字,让孩子知道它应该调用函数来设置状态。
另一种方法是用信号让孩子知道,但在这种情况下,这似乎有点过头了。
总结一下:
- 父进程需要让子进程知道它应该调用一个函数
- 函数将更新子进程的状态(
setState
) - 子进程不需要从父进程接收任何信息
正如您在代码片段中看到的那样,这或多或少就是这种情况。我想知道最好的方法,让孩子的组件调用_updateState
函数时,父母的道具已经改变(不发生在代码片段现在)。
//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>
您可以使用refs
来访问子组件下的所有方法。
参见下面的
https://jsfiddle.net/pranesh_ravi/412j5ucw/这里使用refs
,我在child
内部调用一个函数,它将改变child
组件的状态。
相关文章:
- React js更改状态不会更新组件
- React-状态未更新
- React应用程序:道具在下一个事件后更新
- 如何让React JS点击处理程序在执行时更新DOM
- React:用父级状态更改更新子级
- Universal React/redux未在状态更新时呈现
- 在for循环中未正确更新React本机密钥
- 为什么我的状态在 React.js 中没有更新
- React.js:如何使内联样式在状态更改时自动更新进度条
- React:使用索引变量更新嵌套集合
- React在重新渲染时未更新JSON提要
- 更新时React Redux调度导致递归错误
- React,Flux,React路由器调度错误-可能的批更新解决方案
- 测试React中的点击事件是否会更新HTML
- 如何更新父级的状态'的父组件在react中
- 在Backbone Collections中搜索,使用React更新UI
- 渲染期间的React更新状态会产生错误
- 在IE9中,使用React更新状态不会更新DOM
- 用React更新contentitable容器中的内容
- React更新挣扎