0

我的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

那是因为ChildContextAuthContext. 那么我怎样才能进入some_value里面AuthContext呢?

4

1 回答 1

1

在 React 中,数据会向下流动,因此您的选择是:

  1. ChildContext成为AuthContext.
  2. logout函数移动到它自己的上下文中
function App() {
  const logout = () => {
    /*...*/
  };
  return (
    <LogoutContext value={logout}>
      <AuthContext>
        <ChildContext>
          <Template />
        </ChildContext>
      </AuthContext>
    </LogoutContext>
  );
}
于 2020-10-20T10:01:55.667 回答