购物车总价显示 NaN 而不是总价

时间:2021-04-05 14:27:20

标签: javascript json reactjs e-commerce

所以我目前面临的问题是这个。我在 CartContext 中有一个 Cart 逻辑。除了显示 NAN 的价格总数外,一切正常。这是 CodeSandbox 的链接,以便更好地理解 https://codesandbox.io/s/frosty-sound-5y7pg?file=/src/CartItem.js:1486-1494


import React from "react";


function getCartFromLocalStorage() {
  return localStorage.getItem("cart")
    ? JSON.parse(localStorage.getItem("cart"))
    : [];
}

const CartContext = React.createContext();

function CartProvider({ children }) {
  const [cart, setCart] = React.useState(getCartFromLocalStorage());
  const [total, setTotal] = React.useState(0);
  const [cartItems, setCartItems] = React.useState(0);

  React.useEffect(() => {
    localStorage.setItem("cart", JSON.stringify(cart));

    let newTotal = cart.reduce((total, cartItem) => {
      return (total += cartItem.amount * cartItem.price);
    }, 0);
    newTotal = parseFloat(newTotal.toFixed(2));
    setTotal(newTotal);
    // cart items
    let newCartItems = cart.reduce((total, cartItem) => {
      return (total += cartItem.amount);
    }, 0);
    setCartItems(newCartItems);
  }, [cart]);

  // global functions
  const removeItem = id => {
    setCart([...cart].filter(item => item.id !== id));
  };
  const increaseAmount = id => {
    const newCart = [...cart].map(item => {
      return item.id === id
        ? { ...item, amount: item.amount + 1 }
        : { ...item };
    });
    setCart(newCart);
  };
  const decreaseAmount = (id, amount) => {
    if (amount === 1) {
      removeItem(id);
      return;
    } else {
      const newCart = [...cart].map(item => {
        return item.id === id
          ? { ...item, amount: item.amount - 1 }
          : { ...item };
      });

      setCart(newCart);
    }
  };
  const addToCart = book => {
    const { id, image, by, bookName,RegularPrice } = book;
    const item = [...cart].find(item => item.id === id);

    if (item) {
      increaseAmount(id);
      return;
    } else {
      const newItem = { id, image, by, bookName, RegularPrice, amount: 1 };
      const newCart = [...cart, newItem];
      setCart(newCart);
    }
  };
  const clearCart = () => {
    setCart([]);
  };
  return (
    <CartContext.Provider
      value={{
        cart,
        cartItems,
        total,
        removeItem,
        increaseAmount,
        decreaseAmount,
        addToCart,
        clearCart
      }}
    >
      {children}
    </CartContext.Provider>
  );
}

export { CartContext, CartProvider };

1 个答案:

答案 0 :(得分:0)

你的 CodeSandbox 链接对我来说很好用。总数未显示为 NaN。唯一的问题:将初始数量从 0 更改为 1(CartContext.js,第 48 行):

cart.concat({
  amount: 1,
  /* ... */
})