[英]React HOC to use Context API in Lifecycle method
我正在嘗試創建一個React HOC以在生命周期方法中訪問上下文。
我收到以下錯誤...
(0, _withContext.withContext)
不是一個函數。 (In '(0, _withContext.withContext)(TestScreen)','(0, _withContext.withContext)' is undefined)
該錯誤最有可能在於我使用Context 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'
您沒有明確返回組件,請嘗試以下操作:
const withContext = Component => {
return props => {
return (
<MyContext.Consumer>
{context => {
return <Component {...props} context={context} />;
}}
</MyContext.Consumer>;
);
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.