【问题标题】:LocalStorage item gets overwritten by new itemLocalStorage 项目被新项目覆盖
【发布时间】:2020-03-27 12:43:21
【问题描述】:

我正在尝试使用 LocalStorage,这样每次我添加一个新任务时,它都会添加到 localstorage,但目前它总是会覆盖原来的任务。

我有一个 LocalStorage 的包装器:

export const setLocalStorage = (item) => {    
    localStorage.setItem('todo', JSON.stringify(item));
}

然后我有一个导入包装器的 React 组件,我在该组件中有一个简单的表单,带有一个输入字段和一个按钮:

<Button onClick={(e) => { saveTodo(e) }}> Save Changes </Button>

saveTodo 功能:

constructor(props) {
    super(props)   
    this.state = {
      todo: '',
    }
}

const saveLog = (e) => {
    e.preventDefault();
    setLocalStorage(this.state.todo);
}

现在每次我通过点击按钮执行函数时,LocalStorage 都会被新值覆盖,但我想继续添加到本地存储中

我怎样才能做到这一点?

这是我到目前为止所做的:

export const setLocalStorageItem = (todo) => {
    var todoList = JSON.parse(localStorage.getItem('todo')) || [];
    console.log(todoList);
    todoList.push(todo)
    localStorage.setItem('todo', JSON.stringify(todoList));
}

我在 localsotage 中添加了两项:

Storage {todo: "["hello","123"]", length: 1}
length: 1
todo: "["hello","123"]"
__proto__: Storage

所以现在可以完美运行了:)

【问题讨论】:

  • 保存一个数组到LS,读取它,添加一个新项目并再次写入/保存?
  • ps 你要找的词是“覆盖”
  • 这能回答你的问题吗? adding new objects to localstorage

标签: javascript reactjs


【解决方案1】:

您需要将其从本地存储添加到现有的todo 数组中。像这样的:

export const setLocalStorage = (item) => {    
   const todo = JSON.parse(localStorage.getItem('todo'));
   todo.push(item);
   localStorage.setItem('todo', JSON.stringify(todo));
}

【讨论】:

  • 嘿@symlink 我已经尝试了你的解决方案,我得到了这个: Storage {todo: "1", length: 1} length: 1 todo: "1" proto:存储
  • 嘿,非常感谢你的解决方案工作得很好,但我明白了:我首先将本地存储更改回数组,然后我推送到数组,然后我再次设置?这很混乱,你能解释一下吗?和附言。我必须这样做: const todo = JSON.parse(localStorage.getItem('todo')) || [];避免控制台错误
  • @John 第 2 行:您将 localStorage "todo" 数组读入名为 todo 的本地常量。第 3 行:将当前项目添加到该数组的末尾。第 3 行:将该数组放回 localStorage。
【解决方案2】:

每次输入新数据时,最好将其保存为数组。

localStorage.util.js

export const setItemToLocalStorage = (key, item = []) => {    
    localStorage.setItem(key, JSON.stringify(item));
}

export const getItemFromLocalStorage = (key) => {    
    return JSON.parse(localStorage.getItem(key));
}

组件

constructor(props) {
    super(props)   
    initData();
}
const initData = () => {
    this.setState({
      todo: '',
      todoList: getItemFromLocalStorage('todoList') || []
    });
}
const saveLog = (e) => {
    e.preventDefault();
    setLocalStorage('todoList', [...this.state.todoList, this.state.todo]);
    initData();
}

【讨论】:

    【解决方案3】:
    function saveTodo(newTodo) {
      try {
        const key = "todos";
    
        // Get todos from the storage
        const value = window.localStorage.getItem(key);
    
        let todos = [];
        if (value !== null) {
          // Parse the result into JSON
          todos = JSON.parse(value);
        }
    
        // Push new todo in the list
        todos[todos.length] = newTodo;
    
        // Save the result to the storage
        window.localStorage.setItem(key, todos);
      } catch (error) {
        // Log error
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      相关资源
      最近更新 更多