首页 > 解决方案 > 我可以在 React Native 的 ComponentDidMount 中使用带有异步等待的函数吗?

问题描述

AsyncStorage.getItem在 React Native 中使用。

应用程序加载后,我想使用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)
      }
    }

标签: react-nativeasync-awaitasyncstorage

解决方案


正如评论中提到的,您应该对 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)
    }
  }

推荐阅读