useContext在设置该值后给我在不同组件上未定义的值



我正在为登录创建一个上下文,所以在创建上下文之后,我用该上下文包装了所有路由。并将初始值发送给每个子节点,在我的例子中是useState:

<userContext.Provider value={{loggedUser, setLoggedUser}}>
我有一个组件LogInMenu。它将loggedUser (loggedUser具有用户名/密码结构)设置为一个有效的用户。我在LogInMenu中使用上下文。JSX如下:
const { loggedUser, setLoggedUser } = useContext(userContext)

在控制台成功记录LogInMenu中的loggedUser值后。jsx(只是为了确保它是正确的),我去到我的另一个组件称为Dashboard。jsx并在那里使用上下文,就像我在LogInMenu中使用它一样。jsx,但是这次,如果我控制台记录loggedUser,它会给我一个未定义的值。

注意:我已经在每个使用它的组件中导入了useContext钩子,像这样:

import React, { useState, useContext } from 'react';

和我这样创建的上下文:

import { userContext } from './App';

如果你需要更多的代码来理解这个问题,我可以提供它。

我正在浏览代码沙箱示例,有几点需要考虑尝试将代码移动到提交事件处理程序

const submitData = async (e) => {
e.preventDefault();
// Ideally use post instead of get
// pass user id and password to Api
// password should never be stored in plain text in backend
// depending on the backend store it as hash and authenticate 
// user Id/name and password in the backend
const loginResponse =  await axios.get(`http://localhost:8002/users/${user}`)
if (loginResponse.isSuccess) {
setLoggedUser(loginResponse.userInfo)
}
};

你可以通过他们的新文档了解React。

欢呼

最新更新