Javascript 为什么';更改购物车中的商品数量时,是否进行总价计算?
我很难计算购物车中物品的总成本。我使用了reduce方法,但在我当前的代码中,当您将项目添加到购物车并重定向到结帐时,Javascript 为什么';更改购物车中的商品数量时,是否进行总价计算?,javascript,reactjs,Javascript,Reactjs,我很难计算购物车中物品的总成本。我使用了reduce方法,但在我当前的代码中,当您将项目添加到购物车并重定向到结帐时,total会显示为NaN,除非我弄乱了数量,即使这样也会出现问题。非常感谢您的帮助 Checkout.js: import React, { useContext, useEffect, useState } from "react"; import { Context } from "../../Context"; import Cart
total
会显示为NaN
,除非我弄乱了数量,即使这样也会出现问题。非常感谢您的帮助
Checkout.js:
import React, { useContext, useEffect, useState } from "react";
import { Context } from "../../Context";
import CartItem from "../Cart/CartItem";
function Checkout() {
const { cartItems } = useContext(Context);
let total = cartItems.reduce((sum, { qty, price }) => sum + price * qty, 0); //calculate total
const numberOfItems = cartItems.length === 1 ? `1 item` : `${cartItems.length} items`;
return (
<div>
{cartItems.map(item => (
<CartItem cartItems={cartItems} item={item} key={item.id} />
))}
<p>
{cartItems.length === 0
? "Cart is Empty."
: `You have ${numberOfItems} in your cart.`}
</p>
<h1>Total: ${total}</h1> //appears as NaN on render
</div>
);
}
export default Checkout;
CartItem.js
import React, { useContext } from "react";
import "./cart.css";
import { Context } from "../../Context";
function CartItem({ item }) {
const { increaseQty } = useContext(Context);
item.qty = 1; //assign quantity key to product object
const options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const dropDown = options.map(x => {
return <option key={x}>{x}</option>;
});
return (
<div className="cart-item-container">
<img src={item.url} className="cart-img" />
<span>
{item.itemName}-{item.price}$
</span>
<select onChange={e => increaseQty(item, e.target.value)}>
{dropDown}
</select>
</div>
);
}
export default CartItem;
import React, { useContext } from "react";
import "./cart.css";
import { Context } from "../../Context";
function CartItem({ item }) {
const { increaseQty } = useContext(Context);
item.qty = 1; //assign quantity key to product object
const options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const dropDown = options.map(x => {
return <option key={x}>{x}</option>;
});
return (
<div className="cart-item-container">
<img src={item.url} className="cart-img" />
<span>
{item.itemName}-{item.price}$
</span>
<select onChange={e => increaseQty(item, e.target.value)}>
{dropDown}
</select>
</div>
);
}
export default CartItem;
function increaseQty(product, amount){
cartItems.find(item => item.itemName === product.itemName).qty = amount;
setQty(amount);
};