【发布时间】:2019-12-24 21:54:53
【问题描述】:
我正在使用 react-context 来创建和使用上下文。我无法在上下文提供者的子组件中使用上下文。
我可以访问 App 上下文中的上下文。但是每当我尝试访问单独的组件时,useContext 都会返回 undefined。
我的 App 组件如下所示。
<div className="App">
<Navbar />
<Header/>
<InstructorContextProvider>
<InstructorPage />
</InstructorContextProvider>
</div>
instructorContext 看起来像:
const InstructorContextProvider = (props) => {
const [instructorList] = useState([1,2,3,4]);
return (
<InstructorContext.Provider value = {[...instructorList]}>
{props.children}
</InstructorContext.Provider>
使用 InstructorContext 时,InstructorPage 组件返回 undefined。
const InstructorPage = () => {
const [...instructorList] = useContext(InstructorContext);
console.log(instructorList);
return <h1> hello world </h1>
}
【问题讨论】:
标签: reactjs react-context