【问题标题】:useContext returning undefineduseContext 返回未定义
【发布时间】: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


    【解决方案1】:

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

    此外,如果您查看this codesandbox,一切正常。

    【讨论】:

    • @user10822859 你确定你没有遗漏什么吗?您如何创建 InstructorContext ?在沙盒中,它运行良好
    • 问题是我可以从一些子组件访问上下文,但不是全部。
    • 啊……解决了。对我来说,这是一个简单而愚蠢的错误。这是一个命名的导出,我没有像命名的那样导入它。啊
    • @user10822859 有时会发生
    猜你喜欢
    • 2023-04-06
    • 2020-12-08
    • 2021-07-19
    • 2019-12-13
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多