如果有人可以帮助我,我将不胜感激。
目标:如果通过单击“+”添加的项目:
它需要检查订单是否已经存在(如果存在,则增加数量)
如果没有,则将该项目附加到订单列表中
fullmenu包含以下架构中所有项目的列表:
{ _id: 5eef61450bd95e1f5c8f372f ,
name: "Burger" ,
category: "American" ,
price: "100" ,
isVeg: false,
qty: 0
}
ISSUE:即使它已经存在于订单数组中,它也会添加一个新的 item 对象,而不是仅仅增加它的数量
主要代码逻辑:
const [total, setTotal] = useState(0);
const [orders, setOrders] = useState([]);
const [fullMenu, setFullMenu] = useState();
const addMore = (e) => {
let sign = e.target.innerText;
let id = e.target.id;
const newOrders = [...orders];
let order = newOrders.find(each => each.id === id);
// if the order already exists for the item
if (order) {
let _sign = sign === "+" ? 1 : -1;
// increase or decrease the quantity
order.qty = (order.qty || 0) + 1 * _sign;
// remove item from order list if qty = 0
if(!order.qty){
setOrders(orders => orders.filter(each => each.id !== id));
// setTotal(total => total - parseInt(order.price));
return;
};
// save
setOrders(newOrders);
if (sign === "+") setTotal(total => total + parseInt(order.price));
if (sign === "-") setTotal(total => total - parseInt(order.price));
return;
};
// if item doesn't exist in the order list
const item = fullMenu.find(each => each._id === id);
if (sign === "+") {
order = {
...item, qty: 1
};
setOrders(orders => [...orders, order]);
setTotal(total => total + parseInt(order.price));
};
}
JSX:
<div className="col-sm-4"><span id={each._id} onClick={addMore} category={each.category}>-</span></div>
<div className="col-sm-4"><FormCheckLabel className="qty" >{each.qty}</FormCheckLabel></div>
<div className="col-sm-4"><span id={each._id} onClick={addMore} category={each.category}>+</span></div>
斯蒂芬大帝
杨__羊羊
沧海一幻觉
相关分类