我正在尝试在我的 React Native 应用程序中使用 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);
}
获取数据和存储数据:
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 中的数组,并将 true 或 false 放入该数组的 id 位置。
为什么我从 AsyncStorage 接收该函数而不是我想要的索引数组?
我认为这可能是异步/等待问题,但不知道问题出在哪里。
最佳答案
您的函数“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
}
}
关于javascript - 异步存储返回函数而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184351/