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

React电商项目Cart组件出现TypeError:无法读取undefined的'name'属性

问题根源修复

你的错误出在StateContext.js的onAdd函数里:当购物车已有同款商品时,map循环只返回了匹配到的商品对象,未匹配的商品没有返回值,默认变成undefined,导致cartItems数组混入无效项,在Cart.tsx遍历渲染时访问item.name就会抛出Cannot read properties of undefined错误。

有问题的代码片段

const updatedCartItems = cartItems.map((cartProduct) => {
  if (cartProduct._id === product._id) return {
    ...cartProduct,
    quantity: cartProduct.quantity + quantity
  }
})

这段代码里,map循环仅对匹配到的商品返回新对象,其余项没有return语句,会自动返回undefined,最终updatedCartItems数组里会有多个undefined元素。


修复后的完整onAdd函数

const onAdd = (product, quantity) => {
  const checkProductInCart = cartItems.find(
    (item) => item._id === product._id
  )

  setTotalPrice(
    (prevTotalPrice) => prevTotalPrice + product.price * quantity
  )
  setTotalQuantities(
    (prevTotalQuantities) => prevTotalQuantities + quantity
  )

  if (checkProductInCart) {
    // 修复:确保map每一项都有返回值
    const updatedCartItems = cartItems.map((cartProduct) => {
      if (cartProduct._id === product._id) {
        return {
          ...cartProduct,
          quantity: cartProduct.quantity + quantity
        }
      }
      // 关键:返回未匹配的原商品,避免出现undefined
      return cartProduct
    })

    setCartItems(updatedCartItems);
  } else {
    // 优化:不直接修改原product对象,创建新对象添加quantity
    const newCartItem = { ...product, quantity };
    setCartItems([...cartItems, newCartItem]);
  }

  toast.success(`${quantity} ${product.name} added to the cart.`);
}

额外优化建议

  1. 原代码中直接修改product.quantity = quantity会污染原始商品数据,修复后改为创建新对象,避免副作用。
  2. 可以给Cart.tsx的渲染逻辑加一层空值保护,进一步避免报错:
<h5>{item?.name}</h5>
<h4>₹ {item?.price}</h4>

内容的提问来源于stack exchange,提问作者Krishna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:21:35