React native 我可以在React Native中的ComponentDidMount内使用async await函数吗?
我正在React Native中使用React native 我可以在React Native中的ComponentDidMount内使用async await函数吗?,react-native,async-await,asyncstorage,React Native,Async Await,Asyncstorage,我正在React Native中使用AsyncStorage.getItem 应用程序加载后,我希望使用AsyncStorage.getItem获取设备内存中保存的数据。我想使用ComponentDidMount()。因此,在加载组件后,我希望自动运行AsyncStorage.getItem,并将数据保存到数组数据中。这样,用户就不会按下任何按钮来开始渲染设备内存中保存的内容 我使用了下面的代码,但没有看到任何console.log活动。但是console.log可以在我的其他页面上使用,在这里
AsyncStorage.getItem
应用程序加载后,我希望使用AsyncStorage.getItem
获取设备内存中保存的数据。我想使用ComponentDidMount()
。因此,在加载组件后,我希望自动运行AsyncStorage.getItem
,并将数据保存到数组数据中。这样,用户就不会按下任何按钮来开始渲染设备内存中保存的内容
我使用了下面的代码,但没有看到任何console.log活动。但是console.log可以在我的其他页面上使用,在这里是同一个程序。似乎没有执行组件didmount()
谢谢
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)
}
}
如注释中所述,您应该将异步用于componentDidMount作为:-
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)
}
}
删除异步insinde组件didmount并使用它,就像:async componentDidMount(){…}如果不想使用arrow函数,只需
async componentDidMount(){…}