我正在使用react-context来创建和使用上下文。我无法使用context-provider的子组件中的context。
我可以访问应用程序上下文上的上下文。但是,每当我试图访问单独的组件时,useContext都会返回未定义的。
我的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>
}
发布于 2019-08-19 16:41:54
您不需要使用[...instructorList]
,只需像使用instructorList
一样使用它。
而且,如果你看看this codesandbox,一切都运行得很好。
https://stackoverflow.com/questions/57560801
复制相似问题