我一直在尝试使用最新版本的 @react-native-community/netinfo 和 redux-saga 设置一个事件监听器来获取连接更改,但我无法让它工作。你可以帮帮我吗?
此代码用于在以前的版本中工作:
import { put, take } from "redux-saga/effects";
import { eventChannel } from "redux-saga";
import { NetInfo } from "react-native";
import { OFFLINE, ONLINE } from "redux-offline-queue";
export function* startWatchingNetworkConnectivity() {
const channel = eventChannel(emitter => {
NetInfo.isConnected.addEventListener("connectionChange", emitter);
return () =>
NetInfo.isConnected.removeEventListener("connectionChange", emitter);
});
try {
const isConnected = yield take(channel);
if (isConnected) {
yield put({ type: ONLINE });
} else {
yield put({ type: OFFLINE });
}
} finally {
channel.close();
}
}
现在我有了这个:
import { take, put } from 'redux-saga/effects';
import { eventChannel } from 'redux-saga';
import NetInfo from '@react-native-community/netinfo';
import { OFFLINE, ONLINE } from 'redux-offline-queue';
export function* startWatchingNetworkConnectivity() {
const channel = eventChannel(emitter =>
NetInfo.addEventListener(state => state.isConnected)
);
try {
while (true) {
const isConnected = yield take(channel);
if (isConnected) {
yield put({ type: ONLINE })
} else {
yield put({ type: OFFLINE })
}
}
} finally {
channel.close();
}
}
问候,
埃里克