反应本机 asyncStorage 更新相同的产品数量

react native asyncStorage update same products number pieces

我在我的应用程序中使用异步存储来保存产品名称、颜色、尺寸和件数。 如果它的名称、颜色和尺寸相同,我就不能这样做,我只想增加一块。我想不出..你们能帮帮我吗

try {
      const jsonValue = await AsyncStorage.getItem('shoppingCart');
      let cartitem = [
        {
          ProductDescription: product[0].ProductDescription,
          ItemCode: product[0].ProductCode,
          ColorCode: colorPicked,
          ItemDim1Code: sizePicked,
          Qty1: piece,
          Price: price,
          keyForList: keyForList,
        },
      ];
      if (jsonValue !== null) {
        let newCart = JSON.parse(jsonValue).concat(cartitem);
        AsyncStorage.setItem('shoppingCart', JSON.stringify(newCart));
      } else {
        AsyncStorage.setItem('shoppingCart', JSON.stringify(cartitem));
      }
    }

这样试试:

try {
      let existingCart = await AsyncStorage.getItem('shoppingCart');
      let cartItem = [
        {
          ProductDescription: product[0].ProductDescription,
          ItemCode: product[0].ProductCode,
          ColorCode: colorPicked,
          ItemDim1Code: sizePicked,
          Qty1: piece,
          Price: price,
          keyForList: keyForList,
        },
      ];
      
      if existingCart !== null {
        // We have a cart already, now we have to check if any item in cart is the same as our cartItem; existingCart should be kept as an array
        
        existingCart.forEach((product, index) => {
           if (product.ItemCode == cartItem.ItemCode &&
            product.ItemCode == cartItem.ColorCode) {
            // you can modify this condition by your needs
              existingCart[index].Qty1 += 1
            } 
            else {
              // the item doesn't match any items, therefore we add it to the cart
              existingCart.push(cartItem)
            }
        })
 
      } else {
      // the cart is empty, therefore we put the first item in it
        existingCart = [cartItem]
      }
      
      // and we update the local storage with the cart
     AsyncStorage.setItem('shoppingCart', JSON.stringify(cartitem));

      
    }