【问题标题】:How to make localStorage persist even after reloading of the browser?即使重新加载浏览器,如何使 localStorage 持续存在?
【发布时间】:2020-08-01 08:12:00
【问题描述】:

我用 mongodb 制作了一个 react 应用程序,并使用一个简单的身份验证系统进行了表达。注册后,带有我的凭据的用户模型将保存到 localStorage,如下所示:

{
    bio: ""
    email: "myemail@gmail.com"
    name: "myName"
    role: "user"
    _id: "5e9b42d31040cb0fc54c6936"
}

登录后我想更新 bio 属性,或者添加一些因为初始是空的,所以为了做到这一点,我做了一个这样的 axios 调用:

async function updateBiography (evt) {
        evt.preventDefault();

        try {
            const res = await axios.put(`http://localhost:5000/biography/${id}`, { bioVal });

            setBioVal(res.bio);
        } catch (error) {
            console.log(error);
        }
    }

所以这个东西就是返回bio的更新值,保存到数据库,这里没问题。但我也想在浏览器中更新 bio 的值,我希望在我提交时立即发生。为了实现这一点,我这样做了:

React.useEffect(() => {
    const currentUser = JSON.parse(localStorage.getItem('user'));
    currentUser['bio'] = bioCurrentValue;
    localStorage.setItem('user', JSON.stringify(currentUser));
}, [reload]);

之后localStorage中的item是这样的:

{
    bio: "the new value",
    ...
}

太棒了。我遇到的问题是重新加载浏览器后,localStorage 不会保留更新。 在 localStorage 中重新加载项目后,它会变成以前一样:

{
    bio: "",
    ...
}

如何使更新在 localStorage 中持久保存?

【问题讨论】:

    标签: reactjs mongodb express local-storage


    【解决方案1】:

    本地存储通常是持久的,但您受制于用户的浏览器设置。

    如果在某些隐私浏览模式下,或在使用其他隐私扩展时,存储空间被清除是很常见的。如果这是用户想要的,你无能为力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 2019-03-11
      • 2019-02-24
      • 2021-11-29
      • 1970-01-01
      • 2011-09-13
      • 2014-04-06
      相关资源
      最近更新 更多