我正在尝试创建一个React HOC来访问生命周期方法中的上下文。
我收到以下错误...
(0, _withContext.withContext)
不是函数。 (在“(0, _withContext.withContext)(TestScreen)”中,“(0, _withContext.withContext)”未定义)
错误很可能在于我编写 withContext HOC 的方式。我是编写 HOC 代码的新手。可以帮助指出我的 HOC 的错误在哪里吗?谢谢
在 withContext HOC 中
import { MyContext } from "../context/MyProvider";
const withContext = Component => {
return props => {
<MyContext.Consumer>
{context => {
return <Component {...props} context={context} />;
}}
</MyContext.Consumer>;
};
};
在 TestScreen.js
componentDidMount() {
console.log(this.props.context);
}
export default withContext(TestScreen);
最佳答案
您尚未导出 withContext
函数,因此使用它时会出错
export const withContext = Component => {
return props => {
<MyContext.Consumer>
{context => {
return <Component {...props} context={context} />;
}}
</MyContext.Consumer>;
};
};
然后像这样导入
import { withContext } from 'path/to/withContext'
关于javascript - React HOC 在 Lifecycle 方法中使用 Context API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51020888/