向数组中的对象添加新值后更新 useContext

Updating useContext after adding new value to an object in the array

我有一个购物车,我想根据 select/option 中的用户选择使用新值更新它。 当用户选择数量时,我的 useEffect 触发并将新值添加到我的对象中(确切地说是使用的子元素)。

function ProductData({ price, id }) {
  const [itemsInCart, setItemsInCart] = useContext(ItemsInCartContext);
  const quantity = [1, 2, 3, 4, 5, 6, 7];
  const [chosenQuantity, setChosenQuantity] = useState(1);

  const quantityHandler = (quantity) => {
    setChosenQuantity(quantity.target.value);
  };

  useEffect(() => {
    const updateProductValue = () => {
      const item = itemsInCart.find((item) => item.listing_id === id);

      item.value = chosenQuantity * price;
    };
    updateProductValue();
    // How to update itemsInCart array of objects with new item value?
  }, [chosenQuantity]);

  return (
    <>
      <Quantity>
        Quantity:
        <Select value={chosenQuantity} onChange={(e) => quantityHandler(e)}>
          {quantity.map((number) => (
            <option key={Math.random()} value={number}>
              {number}
            </option>
          ))}
        </Select>
      </Quantity>
      <Price>${price}</Price>
    </>
  );
}

现在我编辑的对象没有存储在本地存储(useContext)中。 我如何更新 useEffect 中的 ItemsInCartContext,以便新值保留在购物车中?

你需要保持状态不可变,还要调用setItemsInCart所以设置它, 直接的方法是映射目标项目 ID:

useEffect(() => {
  setItemsInCart((prev) => {
    const newItems = prev.map((item) => {
      if (item.listing_id !== id) return item;
      return {
        ...item,
        value: chosenQuantity * price,
      };
    });

    return newItems;
  });
}, [chosenQuantity]);