javascript - 是否可以通过反应(钩子)在另一个上下文中使用上下文?
问题描述
当我有两个上下文时,其中一个在另一个上下文中:
...
<ContextOne.Provider value={valueOne}>
<ContextTwo.Provider value={valueTwo}>
{children}
</ContextTwo.Provider>
</ContextOne.Provider>
...
现在是否有可能ContextTwo
使用ContextOne
:
// ContextTwo.jsx
...
const contextOne = useContext(ContextOne);
console.log(contextOne.valueOne); // returns undefined
...
基本上,ContextOne
转换valueOne
为状态(useState
)并ContexTwo
需要使用状态。就我而言, 的值contextOne
在某种程度上是未定义的,而根本没有异步操作。我认为这是可能的,因为ContextTwo.Provider
在里面ContextOne.Provider
?
在这一点上,我真的不知道这是否不可能,或者我的代码总体上是否有问题。
解决方案
是的,有可能,您需要useContext
在ContextTwo
包装器内,例如:
const ContextOne = createContext();
const ContextTwoInner = createContext();
const ContextTwo = ({ value, children }) => {
const valueOne = useContext(ContextOne);
console.log(valueOne);
return (
<ContextTwoInner.Provider value={value}>
{children}
</ContextTwoInner.Provider>
);
};
// For OP's code to work
ContextTwo.Provider = ContextTwo;
// Logs valueOne
const App = () => {
return (
<ContextOne.Provider value={valueOne}>
<ContextTwo.Provider value={valueTwo}>
<div>Hello</div>
</ContextTwo.Provider>
</ContextOne.Provider>
);
};
推荐阅读
- sql - 在 upsert 的准备好的语句中引用现有参数
- elasticsearch - 弹性搜索。按当月搜索数据
- java - Java Color constructor casts long to float
- java - 在模式匹配中排除数字
- excel - Excel VBA:使用用户窗体选择要运行的宏
- java - Java Scanner 出现在 print() 之前
- python - 带有子文件夹的 Django 视图定义在第二次未正确呈现
- fitnesse - 什么决定了fitSharp runner 域名?
- visual-studio-code - 添加了订阅的功能“supportResettableProperties”,但未设置可重置属性
- bash - 从while循环读取文件没有得到第一行