简体   繁体   English

React HOC在生命周期方法中使用上下文API

[英]React HOC to use Context API in Lifecycle method

I am trying to create a React HOC to access the context in a lifecycle method. 我正在尝试创建一个React HOC以在生命周期方法中访问上下文。

I am getting the following error... 我收到以下错误...

(0, _withContext.withContext) is not a function. (0, _withContext.withContext)不是一个函数。 (In '(0, _withContext.withContext)(TestScreen)','(0, _withContext.withContext)' is undefined)

The error most likely lies in the way I wrote withContext HOC. 该错误最有可能在于我使用Context HOC编写的方式。 I am new to writing HOC codes. 我是第一次编写HOC代码。 Can help point out where my error lies for my HOC? 可以帮助指出我的HOC错误在哪里吗? Thanks 谢谢

In withContext HOC 在withContext HOC中

import { MyContext } from "../context/MyProvider";

const withContext = Component => {
  return props => {
    <MyContext.Consumer>
      {context => {
        return <Component {...props} context={context} />;
      }}
    </MyContext.Consumer>;
  };
};

In TestScreen.js 在TestScreen.js中

  componentDidMount() {
    console.log(this.props.context);
  }

export default withContext(TestScreen);

You haven't exported the withContext function and hence its an error in using it 您尚未导出withContext函数,因此使用它时出错

export const withContext = Component => {
  return props => {
    <MyContext.Consumer>
      {context => {
        return <Component {...props} context={context} />;
      }}
    </MyContext.Consumer>;
  };
};

and then import like 然后像导入

import { withContext } from 'path/to/withContext'

You're not explicitly returning your component, try this: 您没有明确返回组件,请尝试以下操作:

const withContext = Component => {
  return props => {
   return (
      <MyContext.Consumer>
        {context => {
          return <Component {...props} context={context} />;
        }}
      </MyContext.Consumer>;
    );
  };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM