如何解决我如何在使用Context API做出反应的购物车中没有重复的价值?
这是我在减速器中用来向购物车中添加物品的代码,下面的return语句是我试图用来不允许购物车中有任何重复物品,而仅更改物品数量的代码。但是它仍然没有用。数量确实会更新,但我仍然会得到重复的值。所以请帮我弄清楚,Thx
export const initialState = {
cart: []
}
const Reducer = (state = initialState,action) =>{
switch(action.type){
case "ADD_TO_CART":
const {id,quantity} = action.item
let alreadyInCart = false,newQty=0
state.cart.forEach(x =>{
if(x.id === id){
alreadyInCart = true
newQty = parseInt(x.quantity+quantity)
}
})
//let categories = [...new Set(Inventory.map(x=>x.category))]
if(!alreadyInCart){
return {
...state,cart: [...state.cart,action.item]
}
} else{
***return { ...state,{...action.item,quantity: newQty} ] }***
}
default:
return state
}
}
export default Reducer
解决方法
看起来您只需要更新购物车中的现有商品,或将其添加到购物车中即可。
尝试一下。
export const initialState = {
cart: [],};
const Reducer = (state = initialState,action) => {
switch (action.type) {
case 'ADD_TO_CART':
const nextCart = [...state.cart];
const existingIndex = nextCart.findIndex((item) => item.id === action.item.id);
if (existingIndex >= 0) {
const newQuantity = parseInt(nextCart[existingIndex].quantity + action.item.quantity);
nextCart[existingIndex] = {
...action.item,quantity: newQuantity,};
} else {
nextCart.push(action.item);
}
return {
...state,cart: nextCart,};
default:
return state;
}
};
export default Reducer;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。