简体   繁体   English

useContext 在子组件中返回未定义

[英]useContext returns undefined in child component

I'm learning hooks and trying to understand useContext .我正在学习hooks并试图理解useContext The component is a child of the provider ,该组件是provider的子组件,

But when I see the value returned by useContext , it is undefined .但是当我看到useContext返回的value时,它是undefined

https://codesandbox.io/s/divine-star-2mz87?file=/src/C2.js https://codesandbox.io/s/divine-star-2mz87?file=/src/C2.js

In the component C2, I get undefined在组件 C2 中,我得到未定义

you should use named import in c2:您应该在 c2 中使用命名导入:

import {CContext} from "./App";

instead of default import which will give you App react component import CContext from "./App";而不是默认导入,它将为您提供App react component import CContext from "./App";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM