gpt4 book ai didi

javascript - 在浏览器的本地存储中保留旧数据

转载 作者:行者123 更新时间:2023-11-30 13:57:47 24 4
gpt4 key购买 nike

我想在单击按钮时保留我的数据。在这段代码中,当前数据成功存储在localStorage中,但是当下一次更新到来时,本地存储被更新。我想存储这两条数据而不覆盖任何内容。

handleSubmit = (e,props) => {
let localStorageArray = [];
let myObj = {name : this.props.UserName,
Email : this.props.email,
Password : this.props.password,
Phone : this.props.phone};
e.preventDefault();
let key = 'Item 1';
localStorage.setItem(key, JSON.stringify(myObj));
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
change={...values};
this.props.changeState(change);
}
});
};

最佳答案

在更新之前,您应该首先获取存储中的内容。

在开始时声明key,然后声明localStorageArray 影响它你当前的存储值:

handleSubmit = (e,props) => {
let key = 'Item 1';
// Retrieves your storage, or initializes it with an empty array if nothing is found.
let localStorageArray = JSON.parse(localStorage.getItem(key) || '[]');
let myObj = {name : this.props.UserName,
Email : this.props.email,
Password : this.props.password,
Phone : this.props.phone};

e.preventDefault();

// Pushes your new object.
localStorageArray.push(myObj);

// Updates your storage.
localStorage.setItem(key, JSON.stringify(localStorageArray));

this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
change={...values};
this.props.changeState(change);
}
});
};

下面是一个工作示例:

// As the document is sandboxed, the following is to simulate the "localStorage".
const CustomStorage = { data: {} };

CustomStorage.getItem = (key) => CustomStorage.data[key];
CustomStorage.setItem = (key, value) => (CustomStorage.data[key] = value);
// ----------

const eAddBtn = document.querySelector('#btn-add'),
eLogBtn = document.querySelector('#btn-log');

// logs the storage's data.
eLogBtn.addEventListener('click', () => console.log(JSON.parse(CustomStorage.getItem('_key') || '[]')));

// Adds an entry into the storage.
eAddBtn.addEventListener('click', () => {
const eInputs = document.querySelectorAll('input'),
storageKey = '_key',
storageItem = JSON.parse(CustomStorage.getItem(storageKey) || '[]'),
obj = {};

Array.from(eInputs).forEach(eInput => obj[eInput.id] = eInput.value);

storageItem.push(obj);

CustomStorage.setItem(storageKey, JSON.stringify(storageItem));
});
<label for="name">
<input id="name" type="text" placeholder="name">
</label>

<label for="age">
<input id="age" type="number" min="0" placeholder="age">
</label>

<button id="btn-add">Add to storage</button>
<button id="btn-log">Log the storage</button>

关于javascript - 在浏览器的本地存储中保留旧数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56885780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com