【问题标题】:React - New Context API not working with Class.contextType, but works with Context.ConsumerReact - 新的 Context API 不适用于 Class.contextType,但适用于 Context.Consumer
【发布时间】:2019-04-06 04:47:05
【问题描述】:

我正在尝试使用返回包装组件的 HOC 的新上下文 API。当我使用Class.contextType = Context 方法时它不起作用:

return function myHOC(WrappedComponent) {
  class HOC extends React.Component {
    // static contextType = MyContext;

    render() {
      console.log(this.context);  // HERE, this logs `{}`

      // ..do stuff
      return <WrappedComponent {...this.props} />
    }
  }
  HOC.contextType = MyContext;

  return HOC;
};

但是,我编写了相同的代码,但使用了&lt;MyContext.Consumer&gt;,它运行良好:

return function myHOC(WrappedComponent) {
  const HOC = (props) => (
    <MyContext.Consumer>
      {(context) => {
        console.log(context);  // HERE, correct values

        return <WrappedComponent {...props} /> 
      }}
    </MyContext.Consumer>
  );

  return HOC;
};

我在这里没有看到什么吗?

【问题讨论】:

标签: reactjs react-context


【解决方案1】:

事实证明,即使我将 react-scripts 更新为 2.0,我也必须自己将 react 更新为 16.6(之前是 16.3)。

我的印象是 react-scripts 也会处理 react 版本。我的错,在那里搞糊涂了。

【讨论】:

  • 我仍在为 console.log(this.context) 获取 {}。更新了 react-scripts 版本和 react 版本。你能帮我吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-23
  • 2018-09-17
  • 1970-01-01
  • 2016-10-26
  • 2021-05-13
相关资源
最近更新 更多