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

React Redux购物车状态更新但商品无法渲染问题求助

React Redux购物车状态更新后无法渲染商品的解决方法

问题根源

你的Cart组件中useSelector的取值路径错误。cartSlice的初始状态是一个包含cart数组的对象({cart: []}),而store中cart键对应的是整个cartSlice的状态对象,直接取state.cart得到的是{cart: [...]},而非实际的商品数组,因此cart.length始终为undefined,组件会错误判定购物车为空。

修复步骤

修改Cart组件中的useSelector,调整取值路径到内部的cart数组:

export default function Cart() {
  // 修正:从state.cart.cart取商品数组
  const cart = useSelector((state) => state.cart.cart);
  console.log("Cart component rendered");

  console.log(cart);

  return (
    <div
      className="cart-container"
      style={{ backgroundImage: `url(${Background})` }}
    >
      <h1>Your Cart</h1>
      {cart.length === 0 ? (
        <p>No items in your cart</p>
      ) : (
        cart.map((item) => (
          <div className="cart-item" key={item.id}>
            <img src={item.image} alt={item.name} />
            <div className="cart-item-details">
              <h3>{item.name}</h3>
              <p>Price: {item.price}DT</p>
            </div>
          </div>
        ))
      )}
    </div>
  );
}

额外验证点

  1. 修正后,控制台打印的cart应该是商品数组,而非包含数组的对象
  2. 确认根组件已正确包裹在Redux的Provider中:
import { Provider } from 'react-redux';
import { store, persistor } from './path-to-store';
import { PersistGate } from 'redux-persist/integration/react';

function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        {/* 你的路由和组件 */}
      </PersistGate>
    </Provider>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:44:52