如何在用户每次添加内容时获取数组的总计?

问题描述 投票:0回答:1

我有一个书店,有书,用户可以将这些书添加到购物车中,然后这些书的总价显示在购物车中,每次他添加新东西时,状态都会添加该数字,问题是用户可以向数组中发送一件物品,所以我想将数量限制为一件稀有物品,我设法限制了显示的书籍,但我不知道之后如何获得总价

以下是我尝试过的:

function BookCard({
  name,
  image,
  price,
  author,
  language,
  description,
  email,
  exchangeable,
  lendable,
  year,
  user,
}) {

  const { setItems, setTotalPrice, items } = useContext(context);

  function addToCart() {
    setItems((prev) => {
      const filteredItems = prev.filter((item) => {
        const oldName = item.name;
        return name !== oldName;
      });

      return [...filteredItems, { name: name, price: price }];
    });

    setTotalPrice((prevPrice) => {
      const [newPrice] = items.slice(-1);

      if (newPrice && newPrice.price !== price) return prevPrice + price;
      else return price;
    });
  }

我的上下文包装器看起来像这样

function CartContext({ children }) {
  const [cartItems, setCartItems] = useState([]);
  const [currentPrice, setCurrentPrice] = useState(0);

  const contextValue = {
    items: cartItems,
    totalPrice: currentPrice,
    setTotalPrice: setCurrentPrice,
    setItems: setCartItems,
  };
  return <context.Provider value={contextValue}>{children}</context.Provider>;
}

我想要什么:

仅添加稀有物品,并获取这些物品的总价,提前致谢

javascript reactjs arrays sorting
1个回答
0
投票

您可以修改 addToCart 函数来处理此逻辑。这是 addToCart 函数的修订版本:

function addToCart() {
  // Check if the item is already in the cart
  const itemIndex = items.findIndex((item) => item.name === name);

  // If the item is not in the cart or it's a rare item, add it to the cart
  if (itemIndex === -1 || isRareItem(name)) {
    setItems((prev) => {
      // Remove any existing occurrences of the same item from the cart
      const filteredItems = prev.filter((item) => item.name !== name);

      // Add the new item to the cart
      return [...filteredItems, { name: name, price: price }];
    });

    // Recalculate the total price based on the current items in the cart
    setTotalPrice((prevPrice) => prevPrice + price);
  }
}

// Function to determine if an item is rare
function isRareItem(itemName) {
  // Implement your logic here to determine if the item is rare
  // For example, you could check against a list of rare items or any other criteria
  // Return true if the item is rare, otherwise return false
  return itemName === "RareItem";
}

在这个修改后的 addToCart 函数中:

  1. 它首先通过在 items 数组中搜索其索引来检查该商品是否已在购物车中。
  2. 如果在购物车中找不到该商品或者它是稀有商品(由 isRareItem 函数确定),则会将该商品添加到购物车。
  3. 然后,它会根据购物车中更新的商品重新计算总价。
© www.soinside.com 2019 - 2024. All rights reserved.