我正在尝试使用react redux制作一个购物车。我可以将产品添加到购物车中,但不知道如何从购物车中删除产品。我试着用拼接的方法去除,但似乎不起作用。
这是我的CarterRedux-
import {createSlice} from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: "cart",
initialState: {
products:[],
quantity:0,
total:0
},
reducers:{
addProduct: (state, action) => {
state.quantity += 1;
state.products.push(action.payload);
state.total += action.payload.price * action.payload.quantity;
},
removeProduct: (state, action) => {
let index = state.products.indexOf(action.payload);
state.quantity -= action.payload
state.products.splice(index, 1)
}
},
});
export const {addProduct} = cartSlice.actions;
export default cartSlice.reducer;
替换数组而不是其内容。
更改线路:
state.products.slice(index, 1)]
通过
state.products.splice(index, 1)
state.products = [...state.products] // clone array
应该允许redux注意到变化。
接收项目ID作为有效负载,然后使用filter方法将其从状态中删除。
const removeItem = state.products.filter((item) => item.id !== action.payload);
state.products = removeItem;
removeProduct:(state,action(=>{state.products.indexOf(action.epayload(;state.products.splice(action.payload,1(};