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

无法从Commerce.js API获取数据,购物车数量实时更新失败报错

解决React + Commerce.js购物车报错及实时更新问题

问题概述

  • 触发报错:
    Cannot read properties of undefined (reading 'total_items')
    TypeError: Cannot read properties of undefined (reading 'total_items')
        at App (http://localhost:3000/static/js/bundle.js:50:20)
        at renderWithHooks (http://localhost:3000/static/js/bundle.js:35235:22)
        at updateFunctionComponent (http://localhost:3000/static/js/bundle.js:38117:24)
        at beginWork (http://localhost:3000/static/js/bundle.js:39829:20)
        at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:24827:18)
        at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:24871:20)
        at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:24928:35)
        at beginWork$1 (http://localhost:3000/static/js/bundle.js:44802:11)
        at performUnitOfWork (http://localhost:3000/static/js/bundle.js:44049:16)
        at workLoopSync (http://localhost:3000/static/js/bundle.js:43972:9)
    
  • 预期效果:点击商品添加到购物车后,Navbar中的购物车数量实时增加
  • 实际情况:点击后触发上述错误,仅刷新页面后购物车数量才会更新

解决方案

1. 修复初始状态与安全属性访问

问题核心是cart状态可能未初始化或变为undefined,导致访问total_items时报错。修改App.jsx的状态初始化与属性访问逻辑:

// App.jsx
import React, { useState, useEffect } from 'react';
import { commerce } from './lib/commerce'
import{ Products, Navbar } from './components'

const App = () => {
  const [products, setProducts] = useState([]);
  // 初始化cart为包含默认值的对象,避免首次渲染报错
  const [cart, setCart] = useState({ total_items: 0 });

  const fetchProducts = async () => {
    const { data } = await commerce.products.list();
    setProducts(data);
  }

  const fetchCart = async () => {
    const cartData = await commerce.cart.retrieve();
    // 兜底处理API返回异常的情况
    setCart(cartData || { total_items: 0 });
  };

  const handleAddToCart = async (productId, quantity) => {
    try {
      const { cart } = await commerce.cart.add(productId, quantity);
      setCart(cart || { total_items: 0 });
    } catch (error) {
      console.error('添加到购物车失败:', error);
    }
  }

  useEffect(()=>{
    fetchProducts();
    fetchCart();
  }, []);

  return (
    <div>
        {/* 用可选链+空值合并确保传递有效数值 */}
        <Navbar totalItems={cart?.total_items ?? 0} />
        <Products products={products} onAddToCart={handleAddToCart}  />
    </div>
  )
}

export default App

2. 修正组件语法错误

  • Product.jsx:移除导出语句末尾的多余逗号
    // 原错误代码
    export default Product,
    // 修正后
    export default Product;
    
  • Navbar.jsx:修复拼写错误并优化样式类名
    // 原错误代码
    <AppBar postion="fixed" className={classes.appBar} color='inherit'>
        <Typography varient="h6" className={classes.appBar} color='inherit'>
    // 修正后
    <AppBar position="fixed" className={classes.appBar} color='inherit'>
        <Typography variant="h6" className={classes.title} color='inherit'>
    

3. 优化Navbar的数值显示

确保Badge始终接收有效数值,避免undefined导致的渲染问题:

// Navbar.jsx
<Badge badgeContent={totalItems ?? 0} color="secondary">
    <ShoppingCart />
</Badge>

原理说明

  • 初始状态设置默认值+可选链操作符,避免组件首次渲染时因cart未就绪导致的属性访问错误。
  • 购物车操作添加错误捕获,确保状态更新的安全性,防止API调用失败破坏现有购物车数据。
  • 修正语法错误保证组件正常渲染,最终实现点击添加购物车后数量实时更新的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:02:00