You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:数组存储对象时数据被覆盖(基于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 data object 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 cartData as an empty array every time the function runs, push only the current item into it, then overwrite the entire cart entry 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") returns null, so we use || "[]" to default to an empty array.
  • Append to the existing array: We push the new item directly to the existingCart array, which preserves all previously added items.
  • Save the full updated array: We overwrite the cart entry 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 08:57:33