【问题标题】:Letting a child know that it should update its state in React让孩子知道它应该在 React 中更新其状态
【发布时间】: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


【解决方案1】:

您可以使用refs 访问子组件下的所有方法。

看下面的小提琴

https://jsfiddle.net/pranesh_ravi/412j5ucw/

这里使用refs,我在child 中调用了一个函数,它将改变child 组件的状态。

【讨论】:

  • 答案的内容必须是现场的,而不仅仅是链接。请注意,Stack Snippets(&lt;&gt; 工具栏按钮)支持 React,因此您根本不需要小提琴。
  • @T.J.Crowder 我的错。将来会使用它。谢谢!
  • 这可能是个好主意,除非有人能告诉我为什么这不是个好主意?我会把这个问题留得更久一点,看看是否有更好的答案。但到目前为止,这似乎是最好的解决方案。
  • @Robin_f 我到处都用它。通过这种方式,您将在组件中定义所有方法,使其可重用。著名的 React 框架也遵循相同的模式。一个很好的例子是 Material-UI
  • @PraneshRavi 你能把我链接到他们使用它的例子吗?我很想看到一个实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 2014-05-14
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多