首页 > 解决方案 > 为什么当我更新一个 useState 时它会更新另一个而不调用它(反应钩子)?

问题描述

我在 react 和编程本身中迈出了第一步,为此我制作了一个简单的购物车,它允许我将要购买的产品添加到以空数组开头的 useState 中。我也有其他使用状态的产品。当我通过具有 addProduct 功能的按钮添加产品​​时,它会验证产品是否已经在列表中,如果是,则如果没有添加,它会增加数量。问题是,当产品已经存在时,它会很好地增加数量,但它也会在处于另一个使用状态的产品中做到这一点。从此我扩展了 chrome 组件,因为当我从购物清单中删除产品并将其放回原处时,它会将它添加到我,但这次是上次的数量。

import React, { useState } from "react";
import { AvailableProductsList } from "./components/AvailableProductsList";
import { ShoppingListCart } from "./components/ShoppingListCart";

export const App = () => {
  // useState that has the products available
  const [products, setProducts] = useState([
    { id: 1, name: "Apple", description: "Apple x 6", amount: 1, price: 3000 },
    { id: 2, name: "Rice", description: "Rice x 1 lb", amount: 1, price: 4000 },
  ]);

  // useState which creates the shopping cart list for me
  const [shoppingList, setShoppingList] = useState([]);

  // Function to add products to the cart or to increase the quantity of some
  const addProduct = (id) => {
    if (shoppingList.some((product) => product.id === id)) {
      const increaseQuantity = shoppingList.map((product) => {
        if (product.id === id) {
          product.amount++;
          return product;
        } else {
          return product;
        }
      });

      setShoppingList(increaseQuantity);
    } else {
      const addNew = products.filter((product) => product.id === id);
      setShoppingList([...shoppingList, ...addNew]);
    }
  };

  // Function to remove products from the shopping list (shopping list cart)
  const removeProduct = (id) => {
    const remove = shoppingList.filter((product) => product.id !== id);
    setShoppingList(remove);
  };

  return (
    <div className="container">
      <div className="row border border-2 border-danger">
        <div className="col-6 border border-info">
          <div className="row">
            {products.map((product) => (
              <AvailableProductsList
                key={product.id}
                product={product}
                addProduct={addProduct}
              />
            ))}
          </div>
        </div>

        <div className="col-6">
          {shoppingList.map((product) => (
            <ShoppingListCart
              key={product.id}
              product={product}
              removeProduct={removeProduct}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

标签: reactjsreact-hooks

解决方案


而不是下面的代码

 if (product.id === id) {
   product.amount++;
   return product;
 } else {
   return product;
 }

将其更改为

if (product.id === id) {
  return { ...product, amount: product.amount + 1 };
}
return product;

产品是从产品数组中引用的。不要直接改变它。创建它的副本,然后进行更改


推荐阅读