[英]How can I add remove items and increment the quantity and increase the price while incrementing or decrementing the quantity of my cart. code by telmo
[英]How can I increase quantity and their prices according to cart of items in cart?
我嘗試了這段代碼,並且一直在為表單和表格單元格使用材質 UI。 此代碼在 localhost:3000 上顯示內容但是當我嘗試單擊增加按鈕時頁面消失了,可能我沒有正確訪問 usestate function。 在這里,通過使用 setProducts 我嘗試臨時更改數量值。 這是一個反應代碼。
const[products,setProducts]=useState([ { 'cartItems':[ { name: 'Cherry', quantity: 1, image:"https://media.istockphoto.com/photos/cherry-trio-with-stem-and-leaf-picture-id157428769?b=1&k=20&m=157428769&s=170667a&w=0&h=F1PxAjsNGhS0svv0t_kMRYdAE3UGISZD_BY066-SubU=", price:200, }, { name:'Almonds', quantity:1, image:"https://media.istockphoto.com/photos/almonds-picture-id153711056?b=1&k=20&m=153711056&s=170667a&w=0&h=8exR9-QE1WweR4ijYM7XdlELsrKBYLQyi7ILRexnHg4=", price:100 }, { name:'Onions', quantity:1, image:'https://media.istockphoto.com/photos/red-onion-slice-picture-id175448479?b=1&k=20&m=175448479&s=170667a&w=0&h=kcjadYpPSifmgaESFhA7EKVMdLmL-pXPhrwSvJM0o2U=', price: 200 } ], 'totalPrice':500, 'count':3 } ]); const handleDecrement = (prod_name) =>{ setProducts(products => products[0].cartItems.map((product) => prod_name===product.name? {...product,quantity:product.quantity-(product.quantity > 1? 1:0)}:product ) ); } const handleIncrement = (prod_name) => { setProducts(products => products[0].cartItems.map((product) => prod_name===product.name? {...product,quantity:product.quantity+1}:product ) ); }
// this is a react code and matrial ui is used in it <TableCell align="left" size="small" width={10}> <form> <div class="value-button" id="decrease" onClick={()=>handleDecrement(product.name)} value="Decrease Value"><RemoveIcon/></div> <input type="number" id='number' value={product.quantity} /> <div class="value-button" id="increase" onClick= {()=>handleIncrement(product.name)} value="Increase Value"><AddIcon/></div> </form> </TableCell>
強文本
你的代碼很接近。 您仍在變異 state。
const handleDecrement = (prod_name) =>{
setProducts((products) => {
const np = [...products];
const np0 = np[0] = {...np[0]};
np0.cartItems = np0.cartItems.map((product) =>
prod_name===product.name ? ({...product, quantity: product.quantity-(product.quantity > 0 ? 1 : 0)}) : product
);
return np;
});
};
const handleIncrement = (prod_name) => {
setProducts(products => {
const np = [...products];
const np0 = np[0] = {...np[0]};
np0.cartItems = np0.cartItems.map((product) =>
prod_name===product.name ? ({...product, quantity:product.quantity + 1}):product
);
return np;
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.