<div className='container py-4 my-5'>
{item.length === 0 ? (
<p>
cart is empty, <NavLink to='/'>continoue shopping</NavLink>
</p>
) : (
item.map((cart) => {
return (
<div className='row py-5 border-bottom'>
<>
<div className='col-md-4'>
<img
src={cart.image}
alt=''
style={{ width: '100%', height: '300px', objectFit: 'contain' }}
/>
</div>
<div className='col-md-4'>
<h3> {cart.title} </h3>
<p className='lead'> {cart.description} </p>
<p>Quantity: {cart.qty}</p>
<strong className='lead fw-bold'>
{' '}
price: {cart.price * cart.qty}{' '}
</strong>
<div className='mt-4'>
<button
className='btn btn-outline-dark me-4'
onClick={() => Decrement(cart)}
>
<i className='fa fa-minus'></i>
</button>
<button
className='btn btn-outline-dark'
onClick={() => addIncrement(cart)}
>
<i className='fa fa-plus'></i>
</button>
</div>
</div>
</>
</div>
);
})
)}
<div className='checkout'>
<h2 className='my-4'>total price: </h2>
<button className='btn btn-outline-dark px-5 py-2 green'>Checkout</button>
</div>
</div>;我用简单的反应在购物车组件中展示产品,我只是搞不懂如何计算所有购物车产品的总价。这是一个基于react的应用程序,我从"useSelector in cart组件中通过映射函数获得数据。是否有可能只计算我刚才添加的所有购物车的总价“。
发布于 2022-06-27 07:26:59
您可以使用reduce函数计算总价:
const [total, setTotal] = useState(0.0);
useEffect(() => {
// Update total when item qty changes
const newTotal = item.reduce((a,b) => (a.qty * a.price) + (b.qty * b.price));
setTotal(newTotal)
}, [item])
...
<div className='checkout'>
<h2 className='my-4'>total price: {total}</h2>
<button className='btn btn-outline-dark px-5 py-2 green'>Checkout</button>
</div>https://stackoverflow.com/questions/72768135
复制相似问题