我正在尝试使用特定值更新我的上下文,但是它并没有更新我认为所谓的全局上下文。
这是我的代码
//CONTEXT
import React, { createContext, useState } from 'react';
export const UserContext = createContext();
export const UserProvider = (props) => {
const [user, setUser] = useState({
name: 'default',
email: 'default@default.com',
pass: 'password',
authenticated: false
});
return (
<UserContext.Provider value={[user, setUser]}>
{props.children}
</UserContext.Provider>
);
}
//Login
function Login() {
const [user , setUser] = useContext(UserContext) ;
const [email, setEmail] = useState({
value: '',
validateOnChange: false,
error: ''
});
const [password, setPassword] = useState({
value: '',
validateOnChange: false,
error: ''
});
const [submitCalled, setSubmitCalled] = useState(false);
const [allFieldsValidated, setAllFieldsValidated] = useState(false);
function loginFunction() {
var temp = {
name: user.name,
email : email.value,
password: password.value ,
authenticated: true
}
setUser(temp);
console.log(`login function ${user.name} email: ${email.value} ${user.email} ${user.password} ${user.authenticated}` )
//Login.js:39 login function default email: Input@email.ca default@default.com undefined false
}
// do other stuff below
问题是正上方的部分(login.js 结尾),如果您看一下,您会看到使用 setUser 更新用户后,电子邮件在之后被调用时不会更改。我正在尝试更新它,以便我可以在整个应用程序中使用名称电子邮件和密码。但我无法让它工作。
//App.js
import logo from './logo.svg';
import Home from './Components/Home';
import Navbar from './Components/Navbar';
import Login from './Components/Login';
import Register from './Components/Register';
import { BrowserRouter, Switch, Route } from "react-router-dom";
import { UserProvider } from './Components/UserContext';
import './App.css';
function App() {
return (
<UserProvider>
<div className="App">
<Navbar />
<BrowserRouter>
<Switch>
<Route path="/home/" exact >
<Home/>
</Route>
<Route path="/login/" exact >
<Login/>
</Route>
<Route path="/register" exact >
<Register/>
</Route>
</Switch>
</BrowserRouter>
</div>
</UserProvider>
);
}
export default App;
感谢您的帮助。节日快乐。
答案 0 :(得分:0)
setState
是异步的,因此在调用 setState
后立即控制台日志时,您永远不会获得当前用户值:
setUser(temp); // async, it takes some time to perform
console.log(`logging some user data ...`); // userState is not yet updated.
// this way you print a state not yet updated
如果你想通过 console.log 更新用户数据,创建一个依赖于用户的 useEffect:
import { useEffect } from "react"
useEffect(() => {
console.log('some user data here')
}, [user])
fwiw,对于真正的应用程序,您永远不应该在浏览器中存储用户敏感数据,例如密码。您应该为此使用令牌或 cookie。