useEffect钩子不更新useState标志,当它被使用时,标志总是保持空



嗨,我正在尝试创建一个身份验证应用程序。要做到这一点,我创建登录DashBoardPage.

这是我的登录码。在我的登录页面代码中,handlessubmit和submit工作正常,并且setAuthenticated, localStorage.setItem("authenticated", true)设置正确。

function Login() {
useEffect(() => {
localStorage.setItem("authenticated", false)
setAuthenticated(false)
}, []);
//const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("")
const [authenticated, setAuthenticated] = useState(localStorage.getItem("authenticated") || false)
const handleSubmit = async () =>{
try{
let res = await api.post("/login", {"email": email, "password":password} )
return res
}catch(e){
console.log("Something Went Wrong")
}

} 
const submit = (e) =>{
if(!email.match(validEmailRegex)){
console.log("Not Valid Mail Address")
}
handleSubmit()
.then(res => {
console.log(res.data.token)
console.log(res.data.message)
setAuthenticated(true) // It shows that it is authenticated
localStorage.setItem("authenticated", true)
})
.catch(error => console.log(error))
}

在登录页面输入真实值后,我去"/DashBoardPage">

这是我的DashBoard代码

import { useEffect, useState } from "react";
import { Redirect } from "react-router-dom";
const Dashboard = () => {

const [authenticated, setAuthenticated] = useState(null);
useEffect(() => {
console.log("Use Effect First Entered",localStorage.getItem("authenticated"))
const loggedInUser = localStorage.getItem("authenticated");

console.log("Logged in user ", loggedInUser)

if (loggedInUser) {
setAuthenticated(true);
}

else {
setAuthenticated(false)
}

}, []);


console.log("const Dashboard Entered",localStorage.getItem("authenticated"))
console.log("EXIT")
console.log("One Before Return", authenticated)
if (!authenticated) {
return <Redirect replace to="/TestPage" />;
} 

if(authenticated) {
return (
<Redirect replace to="/MyProfilePage" />
);
}
};
export default Dashboard;

我这里的问题是authenticated块总是保持空,即使我试图改变他们的值在useEffect在呈现之前。作为一个原因,我不能去我的个人资料页面,总是回到TestPage。有人能解释一下为什么会这样吗?

useEffect中的函数在组件的呈现阶段之后执行。重定向发生在useEffect之前

在剩余的ifs之前添加if (authenticated === null) return null;

额外注意:useState钩子中的setXXX函数不会立即就地更新XXX变量。这个变量只会在下次渲染时更新。

相关内容

  • 没有找到相关文章

最新更新