我正在尝试以本机方式更新asynchStorage
的数据,但是数据没有得到更新。
我遵循了这些线程并以相同的方式进行操作,但是找不到哪里出错了。
尽管如果我尝试仅添加两个工作正常的对象,但是当我尝试将product
添加到productData
时,它仅返回一个旧数据,而productData
不会得到更新。
这是我的jsfiddle。 http://jsfiddle.net/73ftg295/23/
有人可以帮我吗?谢谢。
这是我的摘录
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;
});
};
答案 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