我有这个:
case "ADD_TO_BASKET":
return { items: addProductToBasket(state.items, action), total: calculateTotal(state.items)}
const calculateTotal = (items) => {
return items.reduce((totalPrice, basketItem) => {
const price = basketItem.product.price;
const quantity = basketItem.quantity;
const total = price * quantity;
console.log('here calc2');
return totalPrice + total
}, 0)
}
const addProductToBasket = (items, action) => {
if (isProductInBasket(items, action)) {
return items.map((product) => {
if (product.product.id == action.data.product.id) {
return {...product, quantity: product.quantity + 1}
}
return product;
});
}
else {
const basketState = [].concat(items).concat({...action.data, quantity: 1})
return basketState;
}
}
问题在于,当我调用此功能时,每次正确单击时都会更新项目,但总计始终单击一键。例如,如果我一次称其为20时,总计是0,如果我再次单击它,总计应该是40,但实际上只有20个。?
您应该删除添加的附加参数以减少功能。在初始迭代期间,第一个参数将值为0。尝试使用此
const calculateTotal = (items) => {
let totalPrice = 0
return items.reduce((basketItem) => {
const price = basketItem.product.price;
const quantity = basketItem.quantity;
const total = price * quantity;
console.log('here calc2');
return totalPrice + total
})
}