reactjs - 如何在 Reactjs 中获取购物车中所有产品的总价
问题描述
我有这样的代码
const Cart = ({ fetchCartRequest, productsInCart }) => {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
useEffect(() => {
const userId = localStorage.getItem("userData");
fetchCartRequest(userId);
}, [fetchCartRequest]);
return (
<>
<Image src={CartIcon} alt="Cart icon" onClick={handleShow} />
<Modal show={show} onHide={handleClose} size="md">
<Modal.Header closeButton>
<Modal.Title>Cart detail</Modal.Title>
</Modal.Header>
<Modal.Body>
{!!productsInCart && productsInCart.length > 0 ? (
productsInCart.map((item, index) => {
return (
<CartContainer
key={index}
image={item.image}
name={item.name}
price={parseInt(item.price) * item.quantity}
quantity={item.quantity}
/>
);
})
) : (
<h4 className="center-title">Cart list is empty!</h4>
)}
<div>
<h3>Total price: </h3>
</div>
</Modal.Body>
<Modal.Footer className="d-flex justify-content-center">
<Button btnText="Checkout" onClick={handleClose} />
</Modal.Footer>
</Modal>
</>
);
};
export default Cart;
在我上面的代码中,我已经获得了每件商品的总价,但我还没有获得购物车中所有商品的总价。我想知道,我怎样才能总结购物车中产品的所有价格并在 UI 中显示
解决方案
reduce
简单求和所有项目在js中使用数组:
const Cart = ({ fetchCartRequest, productsInCart }) => {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
useEffect(() => {
const userId = localStorage.getItem("userData");
fetchCartRequest(userId);
}, [fetchCartRequest]);
return (
<>
<Image src={CartIcon} alt="Cart icon" onClick={handleShow} />
<Modal show={show} onHide={handleClose} size="md">
<Modal.Header closeButton>
<Modal.Title>Cart detail</Modal.Title>
</Modal.Header>
<Modal.Body>
{!!productsInCart && productsInCart.length > 0 ? (
productsInCart.map((item, index) => {
return (
<CartContainer
key={index}
image={item.image}
name={item.name}
price={parseInt(item.price) * item.quantity}
quantity={item.quantity}
/>
);
})
) : (
<h4 className="center-title">Cart list is empty!</h4>
)}
<div>
<h3>Total price:
{!!productsInCart && productsInCart.length > 0 ? (
productsInCart.reduce((sum, item) => sum + parseInt(item.price) * item.quantity, 0)
) : null}
</h3>
</div>
</Modal.Body>
<Modal.Footer className="d-flex justify-content-center">
<Button btnText="Checkout" onClick={handleClose} />
</Modal.Footer>
</Modal>
</>
);
};
推荐阅读
- codenameone - 如何从选择器组件中保存选定的值
- spring - Spring Boot 无法连接到 AWS S3 Bucket - IAM 凭证是正确的
- ruby - Ruby如何增加字符串编号
- r - 行之间的 T 检验 - 匹配字符串名称
- ms-access - MSAccess - 超过 2GB 限制或临时空间不足
- jquery - 用于远程验证的 asp.net core 不显眼的表单验证回调
- javascript - Mongo CastError
- sql - 如何使用变量动态设置小数精度
- python - Scipy Gaussian KDE:矩阵不是正定的
- linux - 如何在 Linux 中提高 LLDB 调试启动时间