【问题标题】:How can I delete cart item on index using Redux?如何使用 Redux 删除索引上的购物车项目?
【发布时间】:2021-11-12 17:25:02
【问题描述】:

我想使用 Redux 删除我在购物车中点击的产品。我可以使用“pop”删除产品,但它显然会删除列表中的最后一项,而不是我单击的那一项。每个产品都有自己的价格,我也想从总价格中减去。产品和它的价格在产品列表和shoePrice 列表中具有相同的索引。

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

const cartSlice = createSlice({
    name:"cart",
    initialState:{
        products: [], 
        quantity: 0,
        total: 0,
        shoePrice: [], 
},

reducers:{
    addProduct:(state, action)=>{
        state.quantity += 1;
        state.products.push(action.payload);
        state.shoePrice.push(action.payload.price);
        state.total += action.payload.price;
    },

    removeProduct:(state, action)=>{
        if(state.quantity > 0) {
            state.quantity -= 1;
            state.total = state.total - state.shoePrice.pop(1);
            state.products.pop(1);
        }
    },
  },
});

export const {addProduct, removeProduct} = cartSlice.actions
export default cartSlice.reducer;

【问题讨论】:

标签: javascript reactjs redux


【解决方案1】:

如果您想使用索引从数组中删除产品:

state.products.splice(index, 1)

如果您只想弹出最后添加的产品:

state.products.splice(state.products.length-1, 1)

【讨论】:

    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 2022-08-23
    相关资源
    最近更新 更多