首页 > 解决方案 > useContext 返回未定义

问题描述

我正在使用 react-context 来创建和使用上下文。我无法在上下文提供程序的子组件中使用上下文。

我可以访问 App 上下文中的上下文。但是每当我尝试访问单独的组件时,useContext 都会返回 undefined。

我的 App 组件看起来像这样。

<div className="App">
    <Navbar />
    <Header/>
<InstructorContextProvider>
<InstructorPage />
</InstructorContextProvider>
</div>

讲师上下文看起来像:

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>
}

标签: reactjsreact-context

解决方案


您不需要使用[...instructorList],只需像instructorList.

而且,如果您查看此代码框, 一切正常。


推荐阅读