【发布时间】:2021-02-03 03:15:42
【问题描述】:
我的 app.js 文件中有 2 个上下文:
function App() {
return (
<AuthContext>
<ChildContext>
<Template />
</ChildContext>
</AuthContext>
);
}
当用户注销时,我想访问 ChildContext 内的值,但 logout 函数在 AuthContext 内:
// inside AuthContext:
const myContext = useContext(ChildContext);
const logout = () => {
// doing some stuff..
//
// here is the problem:
console.log(myContext.some_value);
}
错误是:
cannot read property 'some_value' of undefined
这是因为ChildContext 在AuthContext 之后声明。
那么我怎样才能在AuthContext 中到达some_value?
【问题讨论】:
标签: javascript reactjs react-context