我嘗試了一些堆疊示例。我仍然只是重寫我希望添加的內容......主要是每次您檢查它時我們都有一個復選框專案串列我希望現有專案變成這些物件的串列,以便我們可以使用它們“比較”頁面
const handleChange = () => {
localStorage.setItem("item", JSON.stringify(products)); <-- works as expected
var existingItems: any[] = [];
existingItems?.push({ products });
localStorage.setItem("compareItems", JSON.stringify(existingItems));
};
existingItems 總是 = 我想要現有專案的產品 = [{item}, {item},] 等等
產品的詳細資訊:產品(鍵和值的物件 frm api)= {名稱:“產品 1”,描述:“產品 1”,isActiveForEntry:true,displayRank:0,sku:“ABC123”}
uj5u.com熱心網友回復:
在默認為空陣列之前,您必須先獲取現有專案:
const existingItems: any[] = JSON.parse(localStorage.getItem("compareItems")) ?? [];
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
existingItems.push({ products });
localStorage.setItem("compareItems", JSON.stringify(existingItems));
請參閱nullish 合并運算子以了解其??含義。
uj5u.com熱心網友回復:
在每次方法呼叫時,您都在初始化existingItems物件,然后將其值存盤為一項,products因此存盤的物件一次只能保存一項。
您應該檢索compareItems存盤的值,existingItems然后將新物件附加products到它:
const handleChange = () => {
localStorage.setItem("item", JSON.stringify(products));
const compareItems = JSON.parse(localStorage.getItem("compareItems"));
var existingItems: any[] = compareItems ? compareItems : [];
existingItems.push({ products });
localStorage.setItem("compareItems", JSON.stringify(existingItems));
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/524573.html
上一篇:如何在python中調度concurrent.future.Threadpool.executormap()函式
