javascript 无法在useEffect挂接React中设置状态

x6yk4ghg  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(149)

我的项目中有一个导航栏,显示当前登录的用户名,还有一个注销按钮。当我尝试登录时,页面工作正常,jwt auth-token存储在浏览器的本地存储中以维护会话。但在我登录后,如果我刷新网页,那么jwt键将从本地存储中清除。我甚至尝试将状态放在useEffect中的依赖项数组中,但这不起作用。因为在我得到正确的用户值之前,我将退出应用程序。
引用的代码如下:

// part of navbar.js
const { User, getUser } = useContext(NoteContext);
const handleLogout = () => {
    localStorage.removeItem("token");
    // setUser("");
    navigate("/login");
  };

  useEffect(
    () => {
      getUser();
      if (User === "") {
        handleLogout();
      }
    },
    []
    // [User] // even this doesn't work either.
  );
// part of context
const [User, setUser] = useState("");
  const getUser = async () => {
    const response = await fetch(`${host}/api/auth/getuser`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "auth-token": localStorage.getItem("token"),
      },
    });
    if (response.status === 200) {
      const json = await response.json();
      setUser(() => json.user.email);
    } else {
      setUser(() => "");
    }
  };
r8xiu3jd

r8xiu3jd1#

User在下一次渲染之前不会被更新,所以它不会从钩子中的初始值改变。相反,你应该让getUser也返回用户,然后基于此进行检查。

useEffect(
    async () => {
      const newUser = await getUser();
      if (newUser === "") {
        handleLogout();
      }
    },
    []
    // [User] // even this doesn't work either.
  );

  const getUser = async () => {
    const response = await fetch(`${host}/api/auth/getuser`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "auth-token": localStorage.getItem("token"),
      },
    });
    if (response.status === 200) {
      const json = await response.json();
      setUser(() => json.user.email);
      return json.user.email;
    } else {
      setUser(() => "");
      return "";
    }
  };

相关问题