求助:数组存储对象时数据被覆盖(基于sessionStorage购物车场景)
解决sessionStorage中购物车数据被覆盖的问题
Hey, I see exactly what's going on here — every time you trigger the onClick function, you're starting fresh with an empty cartData array instead of adding to the existing cart data stored in sessionStorage. That's why your old entries keep getting overwritten instead of being appended to the list.
Let's break down the problem in your current code:
- You create a single
dataobject with the current item's name and price - You store this single object as
newData(though this step is actually unnecessary, we can skip it) - You initialize
cartDataas an empty array every time the function runs, push only the current item into it, then overwrite the entirecartentry in sessionStorage with this one-item array - Net result: every click replaces the cart with just the latest item, instead of building up a list
Here's the fixed function that appends items correctly:
export function onClick(name: string, price: string) { // Create the new item object (shorthand syntax since variable names match keys) const newItem = { name, price }; // Fetch existing cart data from sessionStorage — if none exists, default to an empty array const existingCart = JSON.parse(sessionStorage.getItem("cart") || "[]"); // Add the new item to the end of the existing cart array existingCart.push(newItem); // Save the updated cart back to sessionStorage sessionStorage.setItem("cart", JSON.stringify(existingCart)); // Log the updated cart to confirm it's working const updatedCart = JSON.parse(sessionStorage.getItem("cart")); console.log(updatedCart); }
Key changes explained:
- Fetch existing cart first: Instead of initializing an empty array every time, we pull the already saved cart data. If it's the first time (no cart exists yet),
sessionStorage.getItem("cart")returnsnull, so we use|| "[]"to default to an empty array. - Append to the existing array: We push the new item directly to the
existingCartarray, which preserves all previously added items. - Save the full updated array: We overwrite the
cartentry in sessionStorage with the now-expanded array, so next time we fetch it, it includes all items.
With this fix, every click will add a new item to your cart array, giving you the exact structure you're expecting:
[ {name:'test1',price:'150'}, {name:'test2',price:'180'}, {name:'test3',price:'190'}, {name:'test4',price:'150'}, {name:'test5',price:'180'}, {name:'test6',price:'190'} ]
内容的提问来源于stack exchange,提问作者user13269954
相关产品推荐
相关产品推荐

