【发布时间】:2021-11-04 04:21:18
【问题描述】:
我正在我的代码中尝试 React 的上下文 API。我尝试了以下代码并收到错误
ReferenceError:初始化前无法访问“MyContextApi”
Context.api.parent.js:
import ContextChildOne from "./Context.api.childone";
import ContextChildTwo from "./Context.api.childtwo";
export const MyContextApi = React.createContext({});
class ContextParent extends React.Component {
render() {
return (
<div>
<p>context api parent tag</p>
<MyContextApi.Provider value={{ concept: "Context API" }}>
<ContextChildOne>
<ContextChildTwo />
</ContextChildOne>
</MyContextApi.Provider>
</div>
);
}
}
export default ContextParent;
我正在以下文件中使用上述上下文 API
Context.api.childtwo.js:
import { MyContextApi } from "./Context.api.parent";
class ContextChildTwo extends React.Component {
// static contextType = MyContextApi;
render() {
// let concept = this.context;
return (
<div>
<p>Child two of context</p>
<p>
THIS IS THE EXAMPLE OF CONTEXT API TO AVOID PROPS DRILLDOWN.
THIS CONCEPT <span>{this.context.concept}</span>
</p>
</div>
);
}
}
ContextChildTwo.contextType = MyContextApi;
export default ContextChildTwo;
我尝试将
export const MyContextApi = React.createContext({});保留在其他文件中并导入它,但它没有用,我得到了同样的错误。请帮我解决这个错误ReferenceError: Cannot access 'MyContextApi' before initialization
【问题讨论】:
标签: reactjs context-api