我有一个cart reducer功能,可以添加、更新和删除 case .我在reduxstore 里也有一个产品array.
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
}
}