我正在为电子商务网站实施购物车。购物车是一个由对象数组表示的状态变量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>
)
Run Code Online (Sandbox Code Playgroud)
这是 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 …Run Code Online (Sandbox Code Playgroud) 为什么document.getElementById("mydiv").style.width不返回 mydiv 的宽度?它返回一个空字符串。有些人建议使用 offsetWidth,但我不明白为什么不能从 style.width 获取它。