react-native - 使用异步函数获取 NetInfo
问题描述
我有一个名为的函数hasNetwork
,我想返回网络连接状态。
当组件获得焦点时,我尝试使用以下代码并调用函数:
constructor(props) {
super(props);
this.props.navigation.addListener('didFocus', () => {
let hasNetwork = this.hasNetwork();
console.log(hasNetwork); // Promise {_40: 0, _65: 0, _55: null, _72: null}
});
}
// ===========================================
// Functions
async hasNetwork() {
await NetInfo.isConnected.fetch().then(isConnected => {
if (isConnected) {
return true;
} else {
return false;
}
});
}
我希望函数返回 true 或 false 但它返回 Promise !。有什么帮助吗?
解决方案
由于hasNetwork
is also async
,您也需要await
使用该功能。要制作匿名函数async
,只需async
在参数之前添加。
此外,由于Network.isConnected.fetch()
返回一个无论如何都会返回真/假值的承诺,因此您可以直接使用它而无需使用then
.
constructor(props) {
super(props);
this.props.navigation.addListener('didFocus', async () => {
let hasNetwork = await Network.isConnected.fetch();
console.log(hasNetwork);
});
}
推荐阅读
- python - 按钮宽度和高度在 tkinter tkmacosx 中不起作用
- c# - 使 xsd.exe 实用程序生成具有强类型的架构
- scala - Scala:从列表创建二叉树
- c++ - 概念中的 C++ 值评估
- html - display flex如何影响元素的行高?
- angular - [已解决]Angular Material Dialog: dialogRef.afterClosed() 订阅未触发
- javascript - 禁用除 div 之外的整个身体
- github - 有没有办法使用 github API 将文件夹上传到 github 存储库
- amazon-web-services - 如何使用 REST API 网关同步运行 AWS Step Functions
- typescript - 如何让 Jest 覆盖仅出口行?