javascript - 处理 React Native 上的 Internet 连接丢失
问题描述
我制作了一个 React Native App,它使用 Android 上的前台服务扫描 BLE 设备。我遇到的问题是处理互联网连接的丢失。一旦互联网可用,当互联网不可用时添加到队列中的待处理操作将不会执行。
一旦检测到信标,我就会使用 NativeModules 向 React Native 发送一个事件,收到该事件后,我会检查互联网是否可用。如果不是,则将其存储在队列中。
const didEnterRegion = async (store, beacons) => {
const { isConnected } = store.getState().connection;
if (isConnected) {
store.dispatch({
type: REQUEST_CHECKIN,
payload: beacons,
});
} else {
NativeModules.BeaconFinder.sendNotification(
'Looks like you entered a venue, but the internet is not reachable.',
beacons.uuid.toString(),
);
store.dispatch({
type: ADD_ACTION_TO_QUEUE,
name: REQUEST_CHECKIN,
payload: beacons,
});
}
};
在 App.js 中,我不断检查互联网连接。如果可用,我将执行队列中的所有操作。
export default class App extends Component {
componentDidMount() {
const unsubscribe = NetInfo.addEventListener(state => {
this._handleConnectionChange(state.isInternetReachable);
});
}
componentWillUnmount() {
//unsubscribe();
}
_handleConnectionChange = isConnected => {
if (isConnected && _.size(store.getState().connection.actionQueue) > 0) {
let queue = store.getState().connection.actionQueue;
_.map(queue, action => {
console.log(action);
store.dispatch({
type: action.name,
payload: action.payload
});
});
}
store.dispatch({
type: CHANGE_CONNECTION_STATUS,
isConnected
});
};
render...
}
这在应用程序处于前台时有效,但是当应用程序从任务切换器中终止时,代码会随机执行,即有时有效,有时无效。
解决方案
推荐阅读
- apache - 将应用程序 URL 重定向到自定义 URL 的步骤
- cordova - 离子刷新器在同步后不会隐藏
- php - 尝试从facebook graph api获取用户具有角色的页面(帐户)的完整列表时如何修复“超出资产访问限制”错误
- testing - 为什么 IAP 产品计数为空?
- postman - 如何在邮递员的每个请求之前运行一组请求
- iis - 从工作组 IIS 安装向 AD 进行身份验证
- windows - 未触发 Windows Installshield 条件
- java - 当文本样式设置为斜体时,android选项卡布局文本隐藏
- google-analytics - 更新 Google Analytics Audience 从 Management API (Python) 返回 500
- ios - 我们如何在自定义表格单元格中实现具有动态内容的动态项目?