How to share data between non parent-child react components?

孤街醉人 提交于 2021-02-10 12:40:28

问题


The procedure for sharing data between components in a child-parent relationship is well documented and dealt with straightforwardly in the React docs. What is less obvious is the accepted way of how one shares state and arbitrary data between components that do not share a child-parent relationship. Flux is offered as a solution, and in the past I have rolled my own pub/sub system, but still there seems a great divide among reactjs developers in this arena. RxJS has been offered as a solution, and many variants on the observer pattern, but I was wondering if there was a more canonical way of managing this issue particularly in larger application where components are less tightly bound.


回答1:


My solution has generally been to pass a callback as a prop to components that will be accepting user input. The callback executes a state change in the parent, which propagates down. For instance:

UI = React.createClass({
  getInitialState() {
    return {
      text: ""
    };
  }

  hello(text) {
    this.setState({
      text: text
    });
  }

  render() {
    return (
      <div>
        <TextView content={this.state.text}>
        <Button onclick={() => this.hello("HELLO WORLD")}>
      </div>
    );
  }
});
// TextView and Button are left as an exercise to the reader

I like this because each parent component is still uniquely responsible for its content, and the child components don't intrusively know anything about each other; it's all callbacks. It admittedly may not scale very well to massive react apps, but I like that there isn't a global event dispatcher managing everything, making control flow hard to follow. In this example, the UI class will always be completely self-contained, and can be replicated as needed without any risk of name reuse.



来源:https://stackoverflow.com/questions/35660618/how-to-share-data-between-non-parent-child-react-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!