监听App中的ReactContext值更改

 收藏

我试图在叶子组件(内部)试图向根组件(App)发送消息的地方使用ReactContext API。在以下示例中,使用上下文公开了Val和用于更新Val的函数。这里的问题是,即使单击“单击我”,也不会在App上调用componentDidUpdate()。

class App extends React.Component {
  static contextType = ThemeContext;

  componentDidUpdate() {
    console.log("update", this.context.val);
  }

  render() {
    return (
      <MyProvider>
        <Inner />
      </MyProvider>
    );
  }
}

class Inner extends React.Component {
  static contextType = ThemeContext;

  render() {
    return <div onClick={() => this.context.load(1234)}>Click me</div>;
  }
}

I've added only relevant code above. Here is a codesandbox for this example. I am expecting componentDidUpdate do be called in App when Click Me is clicked. Basically, i am looking for a way to listen to context changes in the App component.

回复