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

修复Swiggy克隆项目中购物车价格被新商品覆盖的问题

Swiggy克隆项目购物车价格显示问题修复

问题根源

你的cartSlice.js中存在以下关键错误:

  • price状态被错误赋值为单个新增商品的价格,而非购物车所有商品的总价
  • 增减商品数量时的价格计算逻辑错误,误用totalPrice乘以商品数量导致总价异常
  • removeItem方法使用filter获取索引,无法正确定位要删除的商品
  • 折扣和运费计算基于单个商品价格,而非总价

修复后的完整代码

cartSlice.js

import { createSlice } from "@reduxjs/toolkit";

const savedCart = JSON.parse(localStorage.getItem("cart")) || {};

// 辅助函数:计算购物车总价
const calculateTotalPrice = (items) => {
  return items.reduce((total, item) => {
    const itemPrice = item.card.info.price / 100 || item.card.info.defaultPrice / 100;
    return total + (itemPrice * item.count);
  }, 0);
};

const cartSlice = createSlice({
  name: "cart",
  initialState: {
    items: savedCart.items || [],
    totalPrice: calculateTotalPrice(savedCart.items || []),
    discountPrice: 0,
    deliveryFees: 0,
  },
  reducers: {
    addItem: (state, action) => {
      const existingItemIndex = state.items.findIndex(
        (item) => item.card.info.id === action.payload.card.info.id
      );

      if (existingItemIndex !== -1) {
        state.items[existingItemIndex].count += 1;
      } else {
        state.items.push({ card: action.payload.card, count: 1 });
      }

      // 重新计算总价
      state.totalPrice = calculateTotalPrice(state.items);
      // 基于总价计算折扣和运费
      state.discountPrice = (state.totalPrice * 10) / 100;
      state.deliveryFees = (state.totalPrice * 5) / 100;

      localStorage.setItem("cart", JSON.stringify(state));
    },

    removeItem: (state, action) => {
      const itemIdToRemove = action.payload.card.info.id;
      const itemIndexToRemove = state.items.findIndex(
        (item) => item.card.info.id === itemIdToRemove
      );

      if (itemIndexToRemove !== -1) {
        state.items.splice(itemIndexToRemove, 1);
        // 删除后重新计算总价及相关费用
        state.totalPrice = calculateTotalPrice(state.items);
        state.discountPrice = (state.totalPrice * 10) / 100;
        state.deliveryFees = (state.totalPrice * 5) / 100;
      }
      localStorage.setItem("cart", JSON.stringify(state));
    },

    clearCart: (state) => {
      state.items.length = 0;
      state.totalPrice = 0;
      state.discountPrice = 0;
      state.deliveryFees = 0;
      localStorage.setItem("cart", JSON.stringify(state));
    },

    decreaseItemCart: (state, action) => {
      const { id } = action.payload;
      const itemToDecrease = state.items.find(
        (item) => item.card.info.id === id
      );

      if (itemToDecrease && itemToDecrease.count > 1) {
        itemToDecrease.count -= 1;
        // 重新计算总价及相关费用
        state.totalPrice = calculateTotalPrice(state.items);
        state.discountPrice = (state.totalPrice * 10) / 100;
        state.deliveryFees = (state.totalPrice * 2) / 100;
      }
      localStorage.setItem("cart", JSON.stringify(state));
    },

    increaseItemCart: (state, action) => {
      const { id } = action.payload;
      const itemToIncrease = state.items.find(
        (item) => item.card.info.id === id
      );

      if (itemToIncrease) {
        itemToIncrease.count += 1;
        // 重新计算总价及相关费用
        state.totalPrice = calculateTotalPrice(state.items);
        state.discountPrice = (state.totalPrice * 10) / 100;
        state.deliveryFees = (state.totalPrice * 2) / 100;
      }
      localStorage.setItem("cart", JSON.stringify(state));
    },
  },
});

export default cartSlice.reducer;

export const {
  addItem,
  removeItem,
  clearCart,
  decreaseItemCart,
  increaseItemCart,
} = cartSlice.actions;

cart.js 修正点

移除错误的价格显示行,并更新订单摘要的总价引用:

// 移除这一行(使用了错误的全局price状态)
// <p className="font-bold mt-1 text-black inline-block opacity-70">
//   {price.toFixed(2) * menuItem.count}
// </p>

// 保留正确的商品价格计算行
<p>
  ₹{" "}
  {(menuItem.card.info.price.toFixed(2) / 100 ||
    menuItem.card.info.defaultPrice.toFixed(2) / 100) *
    menuItem.count}
</p>

更新订单摘要部分的变量引用:

// 移除不再使用的price变量
// const price = useSelector((store) => store.cart.price);

// 订单摘要中的价格显示改为totalPrice
<div className="price-item flex mb-6 justify-between">
  <p className="text-gray-600">Price ( {CartItem.length} items)</p>
  <p className="font-bold text-lg">₹ {totalPrice.toFixed(2)} </p>
</div>

关键修复说明

  1. 新增辅助函数calculateTotalPrice:遍历购物车所有商品,计算每个商品的单价×数量之和,确保总价准确
  2. 移除冗余的price状态:用totalPrice统一表示购物车总价,避免状态混淆
  3. 修正所有操作后的价格计算:添加、删除、增减数量后,都重新计算总价、折扣和运费
  4. 修复removeItem的索引获取:用findIndex替代filter,正确定位要删除的商品
  5. 修复Cart组件的价格显示:移除基于全局错误价格的计算,改用商品自身的单价计算每个商品的小计

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:20:54