NodeJS useEffect挂钩不更新useState标志,标志在使用时始终保持为空

ix0qys7i  于 2022-12-22  发布在  Node.js
关注(0)|答案(1)|浏览(125)

您好,我正在尝试创建一个身份验证应用程序。为此,我创建了登录页面和DashBoardPage
下面是我的登录代码,在我的登录页面代码中,handleSubmit和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”。
下面是我的 Jmeter 板代码

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中更改它们的值。作为一个原因,我不能后藤MyProfile页面并总是回到TestPage。有人能解释为什么会发生这种情况吗?

pvcm50d1

pvcm50d11#

useEffect中的函数是在组件的呈现阶段之后执行的。因此重定向发生在useEffect之前。
if的其余部分之前添加if (authenticated === null) return null;
补充说明:useState挂钩中的setXXX函数未立即就地更新XXX变量。该变量将仅在下次呈现时更新。

相关问题