1 回答
TA贡献1806条经验 获得超8个赞
看起来localStorage.setItem()会覆盖本地存储中已有的内容。
要在不删除旧条目的情况下更新本地存储中的内容,您可以先读取本地存储内容,合并新项目并写入存储。
const arr = [];
export const addItem = (itemsAddedToCart) => {
const id = Math.random();
arr.push({ ...itemsAddedToCart, id: id });
//get the new elements' ids to a set
const ids = new Set(arr.map(d => d.id));
//read stored items from storage and join them to arr
const storedItems = localStorage.getItem("test");
if(storedItems) {
const storedItemsParsed = JSON.parse(storedItems);
// if the item is not in new items, add them to arr
arr = [..arr, ...storedItemsParsed.filter(item=> !ids.has(item.id)) ]
}
const test = JSON.stringify(arr);
localStorage.setItem("test", test);
return {
type: "ADD_ITEM",
payload: { ...itemsAddedToCart, id: id },
};
};
添加回答
举报