如何更新共享相同 class 的所有组件的状态?

How to update the state of all the components that share the same class?

此组件在我的应用程序中呈现 3 次

class User extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userFavorites: []
    };
    this.postFavorite = this.post.bind(this);
  }

  componentDidMount() {
    this.setState(() => ({
      userFavorites: [{ id: 1, title: "A" }, { id: 2, title: "B" }]
    }));
  }

  post() {
    const obj = { id: 3, title: "C" };
    this.setState(
      prevState => ({
        userFavorites: [...prevState.userFavorites, obj]
      }),
      () => {
        console.log("AFTER", this.state.userFavorites);
      }
    );
  }

  render() {
    return (
      <div className="container">
        <div className="button" onClick={this.post} />
      </div>
    );
  }
}

当我调用 post() 时,通过单击按钮,将 const obj 添加到 userFavorites 数组中,并与上次状态合并。 但是,它仅添加到被单击并触发方法 post().

的 'User'

有什么方法可以在我的应用程序上将状态设置为所有 3 'User component',而不管哪个 'User' 触发状态更新?

三个User组件互不相识。共享状态应该在组件树中移到更高的位置。

下面是一个演示这个想法的小例子。状态存储在 <Parent> 中并作为道具传递给每个 <Child>,连同添加到状态的回调。

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items: [] };
    this.addItem = this.addItem.bind(this);    
  }

  render() {
    return (
      <div>
        <Child name="first" items={this.state.items} add={this.addItem} />
        <Child name="second" items={this.state.items} add={this.addItem} />
        <Child name="third" items={this.state.items} add={this.addItem} />
      </div>
    );
  }
  
  addItem(item) {
    this.setState({ items: [...this.state.items, item] });
  }
}

function Child(props) {
  return (
    <div>
      <h3>{props.name}</h3>
      {props.items.map((item, i) => (<div key={i}>{item}</div>))}
      <button onClick={() => props.add(props.name)}>add</button>
    </div>
  );
}

ReactDOM.render(<Parent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>