【发布时间】:2020-10-09 07:10:13
【问题描述】:
我正在为电子商务网站实施购物车。购物车是一个由对象数组表示的状态变量shopCart。每个对象都包含有关产品的信息,例如标题和价格。我正在尝试实现一个删除按钮,它实际上是在执行它的预期操作,即从 shopCart 状态中删除项目,但屏幕渲染上并未显示更改。我可以清空购物车,但屏幕仍然显示产品。下面是购物车页面的主要代码:
return (
<div class={styles.container}>
<h1>Product</h1><h1>Quantity</h1><h1>Unit price</h1><h1>Total price</h1><div></div>
{
shopCart.map((product, i, array) => <CartItem key={product.id} product={product} index={i} array={array}/>)
}
</div>
)
这里是 CartItem.js 的实现
const CartItem = (props) => {
let { shopCart, setShopCart } = useContext(Context);
let product = props.product;
// takes the identification of a shopping cart product and removes it from the cart
const decrease = (element) => {
shopCart.forEach((el, i) => {
if (el.hasOwnProperty('id')) {
if (el.id === element) {
let aux = shopCart;
aux.splice(i, 1);
setShopCart(aux);
}
}
})
}
return (
<div>
<img src={product.image}></img>
<h1>{product.quantity}</h1>
<h1>{product.price}</h1>
<h1>{product.price * product.quantity}</h1>
<button onClick={() => {
decrease(product.id);
}}>Remove</button>
</div>
)
}
为什么即使每次点击移除按钮后购物车项目都被移除,但它仍无法正确呈现购物车?
【问题讨论】:
-
这能回答你的问题吗? Delete item from state array in react
标签: javascript reactjs