useState 没有在reactjs 中更新,尽管后端是正确的

问题描述 投票:0回答:1

这是我对受保护路由的反应代码:

import React, { useState } from "react";
import { Navigate, Route } from "react-router-dom";

const ProtectedRoute = (props) => {
  const [isAuthenticated, setisAuthenticated] = useState(false);

    const checkALog = async () => {
        const response = await fetch("http://localhost:3000/checkAuth", {
          credentials: "include",
        });
        const data = await response.json();
        console.log("Response from server:", data); 
        if (data.message === "authenticated") {
          setisAuthenticated(true);
        } else {
          setisAuthenticated(false);
        }
    }
    checkALog();

    console.log(isAuthenticated);

  return isAuthenticated ? <Route {...props} /> : <Navigate to="/" />;
};

export default ProtectedRoute;

当我执行 console.log(isAuthenticated); 时,我收到

false
作为控制台消息。并且后端正确地将数据中的消息作为“已验证”

有什么建议吗?我该如何解决这个问题?

尝试询问chatgpt,但没有帮助我。

reactjs react-native react-hooks
1个回答
0
投票

useState 不会改变直接值。在 React 中,当执行任何事件时,每个状态都会发生变化。但没有事件调用你刚刚调用你的函数。 你可以在没有 useState 的情况下实现这一点。

import React, { useState } from "react";
import { Navigate, Route } from "react-router-dom";

const ProtectedRoute = (props) => {
    const isAuthenticated = false;

    const checkALog = async () => {
        const response = await fetch("http://localhost:3000/checkAuth", {
          credentials: "include",
        });
        isAuthenticated = false;
        const data = await response.json();
        console.log("Response from server:", data); 
        if (data.message === "authenticated") {
          isAuthenticated = true;
        }
    }
    checkALog();

    console.log(isAuthenticated);

  return isAuthenticated ? <Route {...props} /> : <Navigate to="/" />;
};

export default ProtectedRoute;

© www.soinside.com 2019 - 2024. All rights reserved.