我有一个推车减速机功能,添加,更新和删除案例.我还在redux商店中有一个产品阵列.如果有两个项目添加到产品数组中,而不是有两个项目,我会增加数量值.我的主要问题是,如果减速器包含任何逻辑,即确定产品阵列是否已包含确切的产品,并且只返回产品数量的更新,或者是否应在演示组件内检查现有产品并添加新产品产品或更新数量?
function CartReducer (state = initialState, action) {
switch (action.type) {
case AddToCart:
return {
...state,
products: [...state.products, action.product],
totalPrice: state.totalPrice += (action.price * action.quantity)
}
case RemoveItemCart:
return {
...state,
products: [
...state.products.slice(0, action.index),
...state.products.slice(action.index + 1)
]
}
case UpdateItemQuantity:
return {
...state,
products: state.products.map((product, index) => {
if (index === action.index) {
return Object.assign({}, product, {
quantity: action.quantity
})
}
return product
})
}
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud)