首页 > 解决方案 > 是否可以通过反应(钩子)在另一个上下文中使用上下文?

问题描述

当我有两个上下文时,其中一个在另一个上下文中:

  ...
    <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

在这一点上,我真的不知道这是否不可能,或者我的代码总体上是否有问题。

标签: javascriptreactjsreact-hooksreact-context

解决方案


是的,有可能,您需要useContextContextTwo包装器内,例如:

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>
  );
};

编辑 fancy-cherry-cy3mq


推荐阅读