让子节点知道它应该在React中更新自己的状态

Letting a child know that it should update its state in React

本文关键字:React 更新 自己的 状态 子节点      更新时间:2023-09-26

我想让子组件知道它应该在父组件的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组件的状态。