reactjs - 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>
}
解决方案
您不需要使用[...instructorList]
,只需像instructorList
.
而且,如果您查看此代码框, 一切正常。
推荐阅读
- c++ - ATL抱怨VS2012之后不包括Windows -> VS2017
- swift - 在 UICollectionView 中滚动时如何保持 pageControl 到位?
- python - 基于多个值之和的字典匹配
- google-cloud-functions - gcp 上的无服务器添加自定义 http 路径
- android - 在android中使用opencv加载YAML模型文件时出错
- css - 在 Progress Tracker 中围绕圆圈画一个环
- c# - WPF 命令绑定与返回 bool 的方法
- javascript - Injector 中提供的 Angular 6 Universal 服务需要另一个应用程序注入变量
- android - 以编程方式更改芯片小部件样式不起作用 - Android
- reactjs - React Native-- node-pre-gyp install --fallback-to-build --library=static_library