react-native - 从 react-native 中的 AsyncStorage 获取项目值
问题描述
我是一个初学者,仍然尝试学习反应原生所以帮助我!
我想在函数外访问 AsyncStorage.getItem 值。我将通过代码进一步解释
这是我的代码:
import {AsyncStorage} from 'react-native';
在 screen1 上设置该值
AsyncStorage.setItem('mobileno', JSON.stringify(MobileNo));
尝试在屏幕 2 上获取该值
AsyncStorage.getItem('mobileno', (err, MobileNumber) => {
let abc = MobileNumber;
console.log("abc value " + abc)
})
let { MobileNo } = abc;
console.log({MobileNo})
我想在函数外部访问该 abc 值,let { MobileNo } = abc;
但它显示错误!
注意: [console.log("abc value " + abc)
完美工作]
错误
找不到变量 abc
问题
那么,我怎样才能访问整个页面的那个 abc 或那个 AsyncStorage 值[在那个函数之外];因为我也想在其他功能中使用该值!
简而言之,我希望 AsyncStorage 中的存储值在其他功能中使用。
感谢您贡献宝贵的时间
解决方案
constructor(props) {
super(props);
this.state = {
mobileNumber: '',
};
}
componentDidMount() {
AsyncStorage.getItem('mobileno').then((mobileNo) => {
if(mobileNo){
this.setState({mobileNumber: mobileNo});
console.log(this.state.mobileNumber);
}
});
}
render() {
return(
<View>
<Text>{this.state.mobileNumber}</Text>
</View>
);
}
在这种情况下 async/await 不是必需的,因为.then()
仅在getItem()
函数完成获取项目后调用。
推荐阅读
- macos - 运行 rsync -av `cat /path/to/file` /destination/ 时在文件路径上转义空格
- java - Hibernate - java.time.LocalDate 不能转换为 java.util.Date
- javascript - 为什么图像在角度 2 中渲染不好
- com - 进程外 COM 注册失败
- node.js - 如何使用 ipinfo.io 在 firebase 函数中获取客户端信息
- jsf - jsf 复合组件的专用处理程序对象
- tortoisegit - Tortoisegit 显示日志 - 没有项目符号的修订是什么意思?
- ios - 如何在swift ios中显示从服务器到手机的任何扩展文件?
- reactjs - 用户登录后更新组件(React / Redux)
- ios - Objective-C 中 sortedArrayUsingComparator 的意外结果