我试图使用Asyncstorage从数据库中获取数据。就像下面这样。
async () => {
var x;
await AsyncStorage.getItem('DB', (err, result) => {
x = result; // I'm getting the data here
});
return JSON.parse(x);// this statement gets executed before I get values from result to x
},
我的问题如下 1)代码放在哪里(在componentDidMount或构造函数中) 2)我应该如何将值输入this.state.dataList
因为在.then of promise中返回另一个承诺,我无法在this.state.dataList中获取值
答案 0 :(得分:1)
当您await
某事时,您正等待Promise解析为某个值。你有点混合旧的做事方式(回调)和新的方式(Promises / async-await)
const x = await AsyncStorage.getItem('DB')
编辑:我看到有一个可选的回调 - 但即使在文档中他们建议只是通过Promise链等待/解析价值
回答你的问题,
componentDidMount
AsyncStorage.getItem('DB').then((result) => this.setState({ dataList: result })