【问题标题】:Modify current object element in javascript in an array修改数组中javascript中的当前对象元素
【发布时间】:2019-01-09 12:46:25
【问题描述】:

我试图在电子商务应用程序中实现本地购物车,所以我有一些类似的产品,每个产品都是一个看起来像这样的对象:

    [
        { prodId: 1, count: 1 },
        { prodId: 2, count: 1 },
        { prodId: 3, count: 1 },
        and so onn...
    ]

现在,如果用户第一次添加产品,它会完美地添加到本地存储中并完美呈现在购物车屏幕上,我所做的就是将该对象存储在本地存储中的 json 字符串中。

此外,如果用户添加具有不同 productId 的产品,它也能正常工作。

但是如果用户再次添加相同的产品,它已经存在于购物车中,我只想增加该 productId 的计数。

    async btnPressed() {
        const item = await AsyncStorage.getItem("obj");
        let val = JSON.parse(item);
        if (val === null) { //Adding a product for first time
            await AsyncStorage.removeItem("obj");
            let newVal = [];
            let count = { counter: 1 };
            let newObj = Object.assign(count, this.props.obj);
            newVal.push(newObj);
            await AsyncStorage.setItem("obj", 
                JSON.stringify(newVal));

            ToastAndroid.showWithGravity(
                "Product added to cart!",
                ToastAndroid.SHORT,
                ToastAndroid.CENTER
            );
         } else {


    //Product is already present, increasing count here
               val.some(element => {
                   if (element.ProductID === this.props.obj.ProductID) {
                       AsyncStorage.removeItem("obj").then(() => console.warn("in val some"));
                       val.pop(element);
                       console.warn(val);
                       element.counter = element.counter + 1;
                       val.push(element);
                       console.warn(val);
                       AsyncStorage.setItem("obj", JSON.stringify(val)).then(() => console.warn("Done"));
                       ToastAndroid.showWithGravity(
                           "Product added to cart!",
                           ToastAndroid.SHORT,
                           ToastAndroid.CENTER
                       );
                       return true;
                   } 
               }); 

    // Adding a new product with different productID

    const checkObj = await AsyncStorage.getItem('obj');
    let fetchedObj = JSON.parse(checkObj);
    if(fetchedObj === null) {}
        let count = { counter: 1 };
        let newObj = Object.assign(count, this.props.obj);
        console.warn(val);
        await AsyncStorage.removeItem("obj");
        val.push(newObj);
        await AsyncStorage.setItem("obj", JSON.stringify(val))
        ToastAndroid.showWithGravity(
            "Product added to cart!",
            ToastAndroid.SHORT,
            ToastAndroid.CENTER
        );
     }
  }

我的逻辑是正确的还是我做错了什么?

【问题讨论】:

    标签: javascript arrays reactjs react-native


    【解决方案1】:

    我认为您应该使用.find() 而不是.some()。有些只是检查是否有至少一个元素满足您的函数内部的评估。由于这些是保持数组不可变的函数,这就是您看不到更改的原因。

    只需从 find 中获取找到的对象,并基于它运行您的逻辑:

    let foundElement = val.find(element => element.ProductID === this.props.obj.ProductID ); 
    

    【讨论】:

      【解决方案2】:

      我会做这样的事情:

      class Cart {
        // Load the cart state
        async load() {
          this.cartContent = JSON.parse(await AsyncStorage.getItem('cart'));
        }
      
        // Save the cart state
        async saveCart() {
          return AsyncStorage.setItem('cart', this.cartContent);
        }
      
        // Add a product into the cart
        async addProduct(productName) {
          // If the cart is empty add the new item
          if (this.cartContent === null) {
            this.cartContent = [{
              name: productName,
              quantity: 1,
            }];
      
            return this.saveCart();
          }
      
          // If the cart is not empty
          // Look if the product already exist
          const product = this.cartContent.find(x => x.name === productName);
      
          if (product) {
            product.quantity += 1;
          } else {
            this.cartContent.push({
              name: productName,
              quantity: 1,
            });
          }
      
          return this.saveCart();
        }
      
        // Remove a product from the cart
        async removeProduct(productName) {
          // You understood what's up now
        }
      }
      
      async addProductBtnPressed() {
        const cart = new Cart();
      
        // Load my cart
        await cart.load();
      
        // Add a new product
        cart.addProduct('whatever');
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-14
        • 2022-11-25
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 2018-10-29
        相关资源
        最近更新 更多