如何在 reactjs 中将用户输入附加到 localStorage 键的单个数组中?
How can I append user inputs in a single array on localStorage key in reactjs?
每次输入新的输入时,我都会尝试将输入附加到本地存储中的数组中。我目前正在使用
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))
就像@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))
每次输入新的输入时,我都会尝试将输入附加到本地存储中的数组中。我目前正在使用
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))
就像@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))