【发布时间】: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;
【问题讨论】:
-
你可以使用
array.filter或者切片,jaketrent.com/post/remove-array-element-without-mutating -
您还可以使用
array.splice(index, 1)删除特定index中的元素。它会改变状态,但它不应该是 redux 工具包的问题。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript reactjs redux