我可以在React Native的ComponentDidMount中使用带有异步等待功能的函数吗?

时间:2019-11-10 16:57:21

标签: react-native async-await asyncstorage

我在React Native中使用AsyncStorage.getItem

应用程序加载后,我想使用AsyncStorage.getItem将保存的数据保存到设备内存中。我想到了使用ComponentDidMount()。因此,一旦加载了组件,我想自动运行AsyncStorage.getItem并将数据保存到数组DATA中。这样,用户将不会按任何按钮来开始呈现保存在设备内存中的内容。

我使用了下面的代码,但是没有看到任何console.log活动。但是console.log可以在同一程序的其他页面上使用。似乎ComponentDidMount()没有执行。

谢谢!

 componentDidMount(){
    async () => { 
      try {
        const HomeData = await AsyncStorage.getItem('@MyApp_Homekey')
        return HomeData
      } catch (e) {
        console.log('There was error.')
      }

      if(!HomeData){
        console.log('There are no Dimmer Light saved in the memory.')
      }
      else {
        console.log('There is value in data after getItem.')
        this.setState(DATA = HomeData)
      }
    }

1 个答案:

答案 0 :(得分:0)

正如评论中提到的那样,您应该对componentDidMount使用async:-


  componentDidMount = async () => {

    const HomeData = await AsyncStorage.getItem('@MyApp_Homekey')

    if(!HomeData){
      console.log('There are no Dimmer Light saved in the memory.')
    }
    else {
      console.log('There is value in data after getItem.')
      this.setState(DATA = HomeData)
    }
  }