作者:pang1995_313 | 来源:互联网 | 2023-01-18 17:55
Facinganissuewheremycartisnotupdatingthequantityandtotalpricecorrectlyafter2quantit
Facing an issue where my cart is not updating the quantity and total price correctly after 2 quantities.
面对我的购物车在2个数量后没有正确更新数量和总价的问题。
Using redux action during my ADD_TO_CART on press button, I will assign a new element into object of quantity:1
在按下按钮的ADD_TO_CART期间使用redux动作,我将为数量对象分配一个新元素:1
export function addToCart(card){
return (dispatch) => {
card.quantity = 1;
dispatch({type: ADD_TO_CART, data:card});
console.log(card);
};
}
On my reducer, here is the function
在我的减速机上,这是功能
let cartState = { data: [], totalPrice: 0 };
const cartReducer = (state = cartState, action) => {
switch (action.type) {
case ADD_TO_CART:
let totalPriceCart = 0;
let checkforDuplicate = state.data.some(function (a){
if(a.sno === action.data.sno){
return true;
}
});
if(checkforDuplicate){
for (let i in state.data) {
if (state.data[i].sno === action.data.sno) {
state.data[i].quantity = action.data.quantity+1;
break;
}
}
for(let e in state.data){
totalPriceCart = totalPriceCart + (state.data[e].price*state.data[e].quantity);
}
return {data: state.data, totalPrice: totalPriceCart };
}
let clOneArr= state.data.concat(action.data);
for(let i in cloneArr){
totalPriceCart = totalPriceCart+(cloneArr[i].price*cloneArr[i].quantity);
}
return {...state, data : cloneArr, totalPrice: totalPriceCart }
default:
return state;
}
};
What am I doing here in the reducer is,
我在减速机里做的是,
- If there is a duplicate item from adding to cart action object (detect by sno), will not concat into the main state array but update the quantity of existing item in the state
如果添加到购物车操作对象(通过sno检测)中存在重复项目,则不会连接到主状态数组但会更新状态中现有项目的数量
Else will concat the array
否则将连接数组
At the end, will count the total price of the whole item in state and pass it back to my cart to show the total based on the quantity*price
最后,将计算整个项目的总价格并将其传回我的购物车,以显示基于数量*价格的总数
Issue is that, currently, my code only shows until 2x, when adding the same item for 3rd time, the quantity will stay at 2x and the price is not calculating correctly.
问题是,目前,我的代码只显示2倍,当第三次添加相同的项目时,数量将保持2倍,价格无法正确计算。
1 个解决方案