1 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
看起來(lái)localStorage.setItem()會(huì)覆蓋本地存儲(chǔ)中已有的內(nèi)容。
要在不刪除舊條目的情況下更新本地存儲(chǔ)中的內(nèi)容,您可以先讀取本地存儲(chǔ)內(nèi)容,合并新項(xiàng)目并寫(xiě)入存儲(chǔ)。
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 },
};
};
添加回答
舉報(bào)