我正在尝试在我的本机应用程序中使用AsyncStorage,但不知道为什么不起作用。
基本上,我想将一个索引数组(或任何键值对)存储在asyncstorage中,对于每个已添加的元素,使用true或false进行存储。
import {AsyncStorage} from 'react-native';
....
componentDidMount() {
this.storeData('favourites', []);
}
addOrRemove(id) {
let favourites = this.getData('favourites');
console.log('favourites getted: ', favourites);
favourites[id] = favourites[id] ? false : true; //this logic is working fine
this.storeData('favourites', favourites);
}
getData和storeData:
storeData = (key, value) => async () => {
try {
await AsyncStorage.setItem(key, value);
} catch (e) {
// saving error
}
};
getData = key => async () => {
try {
const value = await AsyncStorage.getItem(key)
return value;
} catch(e) {
// error reading value
}
};
这就是我做console.log('favourites getted:',favourites);
favourites getted: function _callee2() {
var value;
return _regenerator.default.async(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return _regenerator.default.awrap(_reactNative.AsyncStorage.getItem(key));
case 3:
value = _context2.sent;
return _context2.abrupt("return", value);
case 7:
_context2.prev = 7;
_context2.t0 = _context2["catch"](0);
case 9:
case "end":
return _context2.stop();
}
}
}, null, null, [[0, 7]]);
}
当某人单击特定按钮时,将触发方法addOrRemove(id)
。我想获取存储在AsyncStorage中的数组,并在该数组的id位置放入true或false。
为什么我要从AsyncStorage接收该函数,而不是我想要的索引数组?
我认为这可能是异步/等待问题,但不知道问题出在哪里。
答案 0 :(得分:2)
您的函数“ storeData”和“ getData”返回一个异步函数,您可以简化:
storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (e) {
// process error
}
};
getData = async (key) => {
try {
const value = await AsyncStorage.getItem(key)
return value;
} catch (e) {
// process error
}
};
并与async / await一起使用它们:
componentDidMount() {
this.storeData('favourites', []);
}
async addOrRemove(id) {
try {
let favourites = await this.getData('favourites');
console.log('favourites getted: ', favourites);
favourites[id] = favourites[id] ? false : true;
await this.storeData('favourites', favourites);
} catch (err) {
//process error
}
}