为什么 JSON 对象没有被正确存储?

Why JSON object isn't being stored properly?

我正在使用 React 和 localStorage 功能保持登录会话:

 axios
    .post(url, data, headers)
    .then(resp => {
      if (resp.data.message === "successfully logged in") {
        setAuthenticated(true);
        setUserID(resp.data.id);
        setSessionUsername(resp.data.username);
        setSessionEmail(resp.data.email);
        setDisplayGreeting(true);
        localStorage.setItem("user", resp.data);
        console.log(resp.data);

当我尝试取回 JSON 对象时:

useEffect(() => {
    const loggedInUser = localStorage.getItem("user");
    if (loggedInUser) {
      console.log(loggedInUser);

控制台中的输出显示“Object [object]”。 我做错了什么?

您需要通过将“用户”数据转换为字符串来设置“用户”数据,然后您的数据将以可读格式存储在“存储”选项卡中。这将解决您的 "Object [object]" 问题。

原因是你不能将对象数据存储到localStorage中,它需要字符串,因此你可以将你的对象数据转换成JSON string然后保存。

localStorage.setItem("user", JSON.stringify(resp.data));

为了检索,解析 JSON 它会起作用,就像这样:

const user = JSON.parse(localStorage.getItem("user"))