【发布时间】:2021-05-27 07:53:47
【问题描述】:
所以我正在构建一个购物车,我已经完成了大部分代码,但是当我尝试增加或减少购物车中产品数量的值时,它只会获取我当前数量的值,它没有得到更新. 我无法理解我在哪里犯了错误。
这是我的 cart.js 文件
import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
export default function Cart({ cart, setCart }) {
const getTotalSum = () => {
return cart.reduce(
(sum, { cost, quantity }) => sum + cost * quantity,
0
);
};
const RemoveFromCart = productToRemove => {
setCart(cart.filter(product => product !== productToRemove));
};
const clearCart = () => {
setCart([])
}
const setQuantity = (product, amount) => {
const newCart = [...cart];
newCart.find(item => item.name === product.name)
.quantity = amount;
setCart(newCart)
};
let valueCal =(v)=>{
console.log(v)
return v++
}
let decrement =(v)=>{
console.log(v)
return v--
}
return (
<>
<h1>Cart</h1>
{cart.length > 0 && (<button onClick={clearCart}>Clear Cart</button>)}
<div className="products">
{cart.map((product, idx) => (
<div className="product" key={idx}>
<h3>{product.name}</h3>
<h4>RS: {product.cost}</h4>
<img src={product.image} alt={product.name} />
Quantity: {product.quantity}
<button
value={product.quantity}
onClick={(e) =>
setQuantity(
product,
parseInt(valueCal(e.target.value))
)
}
>Add</button>
<button
value={product.quantity}
onClick={(e) =>
setQuantity(
product,
parseInt(decrement(e.target.value))
)
}
>
Drop
</button>
<button onClick={() => RemoveFromCart(product)}>
Remove
</button>
</div>
))}
</div>
<div>
Total cost: Rs: {getTotalSum()}
</div>
</>
)
}
【问题讨论】:
-
console.log(v)你在这里得到什么? -
任何需要在 React 中改变的东西都必须放在 state 中。
-
@Shyam 我总是得到数量的当前值
-
@GabrielLupu 我会试试的
标签: javascript node.js reactjs react-hooks