无法在React的useEffect钩子中设置状态。

huangapple go评论72阅读模式
英文:

Unable to set state in useEffect hook React

问题

我在我的项目中有一个导航栏,我在其中显示当前登录的用户的名称,并且有一个注销按钮。当我尝试登录时,页面工作正常,jwt授权令牌存储在浏览器的本地存储中以维护会话。但是在登录后,如果我刷新网页,jwt密钥将从本地存储中清除。我甚至尝试将状态放在useEffect的依赖数组中,但这也不起作用,因为在我获得正确的用户值之前,我已从应用程序中注销。

引用的代码如下:

// 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.
  );
// 上下文的一部分
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(() => "");
    }
  };
英文:

I have a navbar in my project where I am displaying the name of the user currently logged in and also has a logout button.
When I try to login the page works fine and the jwt auth-token is stored in the local storage of the browser to maintain session. But after I have logged in, if I refresh the webpage then the jwt key is being cleared from the local storage. I even tried to put the state in the dependency array in useEffect but that doesn't work either because till I get the right user value I am logged out of the application.

The referenced code is as follows:

// 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(() => "");
    }
  };

答案1

得分: 2

User将不会在下一次渲染之前更新,所以它不会从挂钩中的初始值更改。相反,你应该让getUser返回用户,然后根据它进行检查。类似这样的代码应该能够工作:

  useEffect(
    async () => {
      const newUser = await getUser();
      if (newUser === "") {
        handleLogout();
      }
    },
    []
    // [User] // 即使这个也不起作用。
  );

  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 "";
    }
  };
英文:

User will not be updated until the next render, so it will not change from the initial value in that hook. Instead, you should make getUser return the user as well, then check based on that. Something like this should work:

  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 "";
    }
  };

huangapple
  • 本文由 发表于 2023年3月4日 03:20:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定