【问题标题】:How can I append user inputs in a single array on localStorage key in reactjs?如何在 reactjs 的 localStorage 键上的单个数组中附加用户输入?
【发布时间】:2021-11-30 12:32:07
【问题描述】:

每次输入新输入时,我都会尝试将输入附加到本地存储中的数组中。我目前正在使用 localStorage.setItem('Inputs', JSON.stringify(document.getElementById("inputVal").value)) 获取值但不将其添加到任何数组中,而是替换先前的值。我将如何着手将输入添加到本地存储的数组中?我也想知道我是否可以使用.appendChild()

快速更新: 我也试过了

var valueS = document.getElementById("inputVal").value;
    const arr = [];
    const newArry = [
      ...arr,
      valueS
    ]
    //arr.push(valueS)
    localStorage.setItem('Data', JSON.stringify(newArry))

【问题讨论】:

  • 您需要加载之前存储在本地存储中的 JSON 并将其分配给您的 arr 变量。现在你只需覆盖它。
  • const arr = []; 应该是localStorage的数组,第一次设置时应该是新数组
  • 你正在将一个空数组传播到 newArry 中,它如何包含以前的 localStorage?

标签: javascript reactjs reactstrap


【解决方案1】:

就像@nIta、@Patrick Evans 和@David Grosh 指出的那样,const arr = [] 应该包含本地存储数组。

适合我的解决方案如下:

var valueS = document.getElementById("inputVal").value;
    const arr = [JSON.parse(localStorage.getItem('Data'))];
    const newArry = [
      ...arr,
      valueS
    ]
    localStorage.setItem('Data', JSON.stringify(newArry))

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2018-12-06
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多