react-native - 我可以在 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)
}
}
解决方案
正如评论中提到的,您应该对 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)
}
}
推荐阅读
- c++ - 错误:使用已删除的函数 'ClassName::ClassName(const ClassName&)'
- c++ - 在CGAL中获取两个圆的交点
- ios - 有效登录后React Native iOS“Safari无法打开页面,因为地址无效”
- c# - 如何在 UWP 中通过标题名称数据网格获取列值
- elixir - 如何为 Ecto 迁移中的小数列设置默认值?
- sql - 添加外键约束时出错?
- vue.js - Vuejs:无法解析文件'particles.js'
- angular - 名称为“recaptchaReactive”的表单控件没有值访问器
- javascript - CSS Grid - 向上移动一行的最佳方式?
- r - 正则表达式,根据标点符号 R 分隔?