javascript - 在 View 更改时 react JS 本地存储更新

标签 javascript reactjs local-storage

如何在整个用户旅程中输入新数据时更新本地存储项目或对象的某些属性,而不丢失之前输入的内容或用户决定更新?

我的 5 个容器之旅包括要求用户输入以下内容:

  • 姓名:字符串
  • 头像:整数
  • 最喜欢的流派:多个字符串

在第一个 View 中,我创建了在 handleSubmit 函数中设置名称的本地存储对象/项目。

处理提交(事件){ event.preventDefault();

//Profile object
let profile = { 'name': this.state.name, 'avatar': null, 'genres': '' };

// Put the object into storage
localStorage.setItem('profile', JSON.stringify(profile));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('profile');

//Log object
console.log('retrievedObject: ', JSON.parse(retrievedObject));

//On form submission update view
this.props.history.push('/profile/hello');

在我的第二个 View 中,我只想更新 avatar 属性并保留用户在前一个 View 中输入的内容。

我在 handleSelect 函数中这样做:

handleSelect(i) {
    let selectedAvatarId;
    let avatars = this.state.avatars;

    avatars = avatars.map((val, index) => {
      val.isActive = index === i ? true : false;
      return val;
    });

    this.setState({
      selectedAvatarId: selectedAvatarId
    })

    //Profile object
    let profile = { 'avatar': i };

    //Update local storage with selected avatar
    localStorage.setItem('profile', JSON.stringify(profile));
  }

最佳答案

您需要从 localStorage 读取现有值,将其解析为 JSON,然后操作数据,然后将其写回。有许多库可以轻松地与 localStorage 一起使用,但是与此类似的东西应该作为通用函数工作:

function updateProfile = (updatedData) => {
    const profile = JSON.parse(localStorage.getItem('profile'));
    Object.keys(updatedData).forEach((key) => {
        profile[key] = updatedData[key];
    });
    localStorage.setItem('profile', JSON.stringify(profile));
}

如果你使用 object spread,它看起来也会更干净:

function updateProfile = (updatedData) => {
    const profile = {
        ...JSON.parse(localStorage.getItem('profile')),
        ...updatedData
    };
    localStorage.setItem('profile', JSON.stringify(profile));
}

上面的代码可能应该有一些安全检查,但希望能给你一个起点的想法。

关于javascript - 在 View 更改时 react JS 本地存储更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50702032/

相关文章:

javascript - 我如何才能唯一地选择我当前 Blogger 帖子的本地元素,而不是整个文档中的元素?

database - Phonegap如何在android上保存永久数据

javascript - 本地存储可观察服务上的主题切换器

javascript - 创建交互式 map

javascript - 使用 jQuery 获取特定的 iFrame 类(或获取 CKEditor 值)

javascript - 浏览器加载损坏的旧 Javascript

reactjs - React Antd 模态属性 'children' 在类型 'IntrinsicAttributes & ModalProps' 上不存在

reactjs - React 项目 WAR 文件

node.js - 为什么 mongoDB 不会更新我的用户条目的 “Date” 字段?

javascript - 无法使用 .removeItem 删除 LocalStorage 项目