如何使用 Redux 和 React js 在购物车页面中添加和删除总价

问题描述 投票:0回答:1

React JS 的开发者大家好! 我是第一次使用 Redux 和 React Js 并尝试获取购物车中添加和删除的商品的总价,但是当删除一个商品时总价只增加而没有减少。

我正在使用 reducer,我几乎可以肯定这里实现了那里的逻辑,但有一天我会非常陷入这个麻烦

这是我在 CartRedux.js 中的代码 Reducer

const cartSlice = createSlice({
  name: "cart",
  initialState: {
    products: [],
    quantity: 0,
    total: 0,
  },
  reducers: {
    addProduct: (state, action) => {
      state.quantity += 1;
      state.products.push((product) => product._id === action.payload);
      state.total += action.payload.price * action.payload.quantity;
    },
    clearCart: (state) => {
      state.products = [];
    },
    deleteProductStart: (state) => {
      state.isFetching = true;
      state.error = false;
    },
    deleteProductSuccess: (state, action) => {
      state.isFetching = false;
      state.quantity -= 1;
      state.products.splice(
        state.products.findIndex((item) => item._id === action.payload),
        1
      );
      //agregar aquí la función para restar el total en el RESUMEN DE COMPRA
    },
    deleteProductFailure: (state) => {
      state.isFetching = false;
      state.error = true;
    },
  }
});
reactjs redux shopping-cart
1个回答
0
投票

您可以使用数组过滤方法从数组中删除特定元素而不改变原始状态。

state.products = state.products.filter(element => element._id !== action.payload);

或者你可以使用 slice 从你的状态中删除元素:

state.products = [
    ...state.products.slice(0, action.payload),
    ...state.products.slice(action.payload + 1)
],

此外,当您从您的状态中删除一项时,您并没有减少您的总价值。

state.total -= action.payload.price * action.payload.quantity;

总而言之,您的 deleteProductSuccess 函数应该如下所示:

deleteProductSuccess: (state, action) => {
      state.isFetching = false;
      state.quantity -= 1;
      state.products = state.products.filter(element => element._id !== action.payload);
      state.total -= action.payload.price * action.payload.quantity;
},
© www.soinside.com 2019 - 2024. All rights reserved.