【问题标题】:Best practice to get data from Asyncstorage database in react nativereact native 从异步存储数据库获取数据的最佳实践
【发布时间】:2018-08-14 16:04:45
【问题描述】:

我尝试使用 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 返回另一个 promise 我无法在 this.state.dataList 中获取值

【问题讨论】:

    标签: android ios reactjs react-native asyncstorage


    【解决方案1】:

    当您 await 某事时,您正在等待 Promise 解析为一个值。您有点混合了做某事的旧方式(回调)和新方式(Promises/async-await)

    const x = await AsyncStorage.getItem('DB')

    编辑:我看到有一个可选的回调 - 但即使在文档中,他们也建议通过 Promise 链等待/解析值

    回答你的问题,

    1. 因为你在设置状态,所以应该放在componentDidMount
    2. AsyncStorage.getItem('DB').then((result) => this.setState({ dataList: result })

    【讨论】:

    • 你不能只使用 await 没有异步函数
    猜你喜欢
    • 2011-03-23
    • 2012-04-28
    • 2023-02-06
    • 2020-08-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多