【问题标题】:How to get a component to pass state to parent's sibling如何让组件将状态传递给父级的兄弟姐妹
【发布时间】:2017-10-24 05:40:09
【问题描述】:

我有如下所示的组件

组件 1 --- 组件 3
|
组件2
|
组件4

组件 2 和 3 是 1 的子代,组件 4 是 2 的子代。 我需要将我存储为状态的 Component4 中的数据传递给 Component3,后者将显示它。我认为这样做的方法是将状态从 Component4 传递到 Component2,后者将使用回调进一步将状态发送到 Component1,最后 Component1 将状态向下传递给 Component3。这是最好的方法吗?

【问题讨论】:

  • this great article关于在不使用 Flux(或 Redux)的情况下在组件之间共享数据的不同策略......但我只会使用 Redux。

标签: reactjs


【解决方案1】:

将数据存储在状态最高的公共父级(组件 1)中。在 component1 上创建操作此状态的方法并在构造函数中将 this 绑定到它们。然后将状态传递给 component3。

class component1 extends React.Component {
   constuctor(props) {
     super(props);
     this.stateChanger = this.stateChanger.bind(this)
     this.state = {
       foo: 'bar'
     }
   }
   stateChanger(e) {
      this.setState({ foo: 'baz' })
   }
   render() {
    <Component3 foo={this.state.foo} />
    <Component2 stateChanger={this.stateChanger} />
   }
}

编辑:将 stateChanger 函数传递给 component4,如下所示:

class Component2 extends React.Component {
  render() {
    return (
      <div>
        <Component4 stateChanger={this.props.stateChanger} />
      </div>
    )
  }
}

然后用它做你想做的事。 Here is an article you should check out!

【讨论】:

  • 组件4是用组件2编写的。 Component1 渲染 Component2,后者将渲染 Component4
【解决方案2】:

回调将起作用。另一种常见的解决方案是提升状态。

不用将状态存储在 Component4 中,只需将状态移动到 Component1 并将它们作为 props 传递给 Component3 和 4。

我个人不喜欢很长的回调链,提升状态通常对我来说感觉更好。

如果您有很多状态需要在组件之间共享,您应该开始考虑使用状态管理解决方案,例如 Redux 或 MobX 等。

【讨论】:

  • redux 是指使用 mapStatetoProps 吗?
  • 是的,只需将组件与商店连接
【解决方案3】:

解决此问题的最佳且可扩展的解决方案是使用有助于双向数据流的 FluxRedux。他们有一个存储数据的商店,我们可以随时访问和修改可供所有组件使用的数据。

看看 Redux,你可以找到使用 Redux 实现的示例here

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2018-09-02
    • 2021-01-30
    • 2017-12-01
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多