如何使用Redux删除购物车指定索引商品并同步更新总金额?
Redux Toolkit 购物车删除指定商品解决方案
问题原因
pop()方法本身不支持传入参数指定删除位置,功能固定为删除数组的最后一位元素,因此你现在的写法只能删除最后一个商品- 现有
removeProductreducer没有接收目标商品的定位参数,无法定位到你点击的对应商品
修改步骤
1. 调用删除接口时传入商品索引
在渲染购物车列表的组件中,遍历products数组时拿到当前商品的索引,调用removeProduct时将索引作为参数传入:
// 购物车列表渲染示例 {products.map((item, index) => ( <div key={item.id}> <span>{item.name}</span> <button onClick={() => dispatch(removeProduct(index))}>删除</button> </div> ))}
2. 重写removeProduct reducer逻辑
使用支持指定位置删除的splice()方法操作数组,由于products和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)=>{ const deleteIndex = action.payload; // 先判断索引合法性,避免异常报错 if(state.quantity > 0 && deleteIndex >=0 && deleteIndex < state.products.length) { state.quantity -= 1; // 扣除对应商品价格 state.total -= state.shoePrice[deleteIndex]; // 删除两个数组中对应索引的元素 state.shoePrice.splice(deleteIndex, 1); state.products.splice(deleteIndex, 1); } }, }, }); export const {addProduct, removeProduct} = cartSlice.actions export default cartSlice.reducer;
内容的提问来源于stack exchange,提问作者Kol256
相关产品推荐
相关产品推荐

