首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >useContext返回未定义

useContext返回未定义
EN

Stack Overflow用户
提问于 2019-08-20 00:39:39
回答 1查看 2.5K关注 0票数 1

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

我可以访问应用程序上下文上的上下文。但是,每当我试图访问单独的组件时,useContext都会返回未定义的。

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

代码语言:javascript
复制
<div className="App">
    <Navbar />
    <Header/>
<InstructorContextProvider>
<InstructorPage />
</InstructorContextProvider>
</div>

instructorContext如下所示:

代码语言:javascript
复制
const InstructorContextProvider = (props) => {
const [instructorList] = useState([1,2,3,4]); 
return (
   <InstructorContext.Provider value = {[...instructorList]}>
       {props.children}
   </InstructorContext.Provider>

使用InstructorContext时,InstructorPage组件返回undefined。

代码语言:javascript
复制
const InstructorPage = () => {
const [...instructorList] = useContext(InstructorContext);
console.log(instructorList);
return <h1> hello world </h1>
}
EN

回答 1

Stack Overflow用户

发布于 2019-08-20 00:41:54

您不需要使用[...instructorList],只需像使用instructorList一样使用它。

而且,如果你看看this codesandbox,一切都运行得很好。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57560801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档