React Native AsyncStorage:无法解析getItem返回的promise

问题描述 投票:2回答:1

我有以下代码应该从AsyncStorage返回一个项目。

但是该项目永远不会被阅读:

const key = 'shoppingListItems';

export default class ShoppingListService {
    static async getItems() 
    {
        let result = await AsyncStorage.getItem(key);

        return result;
    }

    // ...
}

我在一个组件(屏幕)中使用它:

// ...

  componentDidMount()
  {
    alert(JSON.stringify(ShoppingListService.getItems()));
  }

// ...

它总是向我显示一条消息:

{ “_40” 0, “_ 65” 0, “_ 55”:空, “_ 72”:空}

如何获取AsyncStorage中的数据?

reactjs react-native asyncstorage
1个回答
3
投票
  async componentDidMount()
  {
    alert(JSON.stringify(await ShoppingListService.getItems()));
  }

我做了componentDidMount函数async。我不知道是否推荐,但这有效。

© www.soinside.com 2019 - 2024. All rights reserved.