在React Native中AsyncStorage的数据不会被新数据更新

时间:2018-06-21 17:36:24

标签: javascript reactjs react-native

我正在尝试以本机方式更新asynchStorage的数据,但是数据没有得到更新。

我遵循了这些线程并以相同的方式进行操作,但是找不到哪里出错了。 尽管如果我尝试仅添加两个工作正常的对象,但是当我尝试将product添加到productData时,它仅返回一个旧数据,而productData不会得到更新。 这是我的jsfiddle。 http://jsfiddle.net/73ftg295/23/

有人可以帮我吗?谢谢。

  1. What is the correct way to use AsyncStorage to update state in React-Native?
  2. How can I add a key/value pair to a JavaScript object?

这是我的摘录

static addToCart(id,name,qty,price){

//Storing the data into a variable 
        let product={
            id:id,
            name:name,
            qty:qty,
            price:price,

        };

      //Generate rowid for the product
      product.rowId = this.generateHash(product);

   //Calling asyncStorage function     
 AsyncStorage.getItem('CART').then((data) => {

                    //Check if the data exist or not
            if (data !== null){

                //Convert the data to an object and store to productData variable
                let productData= JSON.parse(data);

                //Check if the product with the rowid exist in the store or not
                if (this.checkIfExist(product.rowId)){

                //If exist increment the quantity of the product
                    productData[product.rowId].qty += product.qty;
                }else{

                    //If does not exist then add this new product to the existing products
                    productData[product.rowId] = product;  // ERROR HERE !! the new record is not getting added to the productData


                }

                //Update the storage with new data
                AsyncStorage.setItem("CART", JSON.stringify(productData)).done();
                cartResponse = productData;
            }else{
            //If data is null then there is no previous product availabe. Add first product
                let cartItem ={};
                cartItem[product.rowId] =product;
                AsyncStorage.setItem("CART", JSON.stringify(cartItem)).done();
            }

            //If everything works fine then return true
            return true;
        }).catch((error)=>{
            console.log('Error occurred while adding product to cart',error);
            return false;
        });

};

1 个答案:

答案 0 :(得分:0)

AsyncStorage是异步的,因此您可以像这样用await进行呼叫:

try {
  const value = await AsyncStorage.getItem('@MySuperStore:key');
  if (value !== null){
    // We have data!!
    console.log(value);
  }
} catch (error) {
  // Error retrieving data
}

这是来自Facebook的文档,很容易理解: https://facebook.github.io/react-native/docs/asyncstorage.html#docsNav