如果我的应用程序与互联网断开超过5分钟,我想清除本地应用程序的数据。
我正在使用react本机NetInfo检查网络连接状态。节省应用程序断开连接的时间,并检查它何时将重新连接到internet。如果间隔超过5分钟,那么我想清除应用程序数据。
我的守则是:
class OfflineMessage extends PureComponent {
constructor(props) {
super(props);
this.state = {
isConnected: true
};
}
componentDidMount() {
NetInfo.addEventListener((state) => {
this.handleConnection(state.isConnected);
});
}
componentWillUnmount() {
NetInfo.removeEventListener((state) => {
this.handleConnection(state.isConnected);
});
}
handleConnection = (isConnected) => {
this.setState({ isConnected });
if(!isConnected){
this.startTimer();
} else {
this.checkElapsed();
}
};
startTimer = async () => {
try {
console.log('Internet disconnected at: ');
await AsyncStorage.setItem('time', JSON.stringify(Date.now()));
} catch (error) {
// console.log('Something went wrong', error);
}
}
checkElapsed = async () => {
try {
let startTime = await AsyncStorage.getItem('time');
if(startTime){
let endTime = Date.now();
const elapsedTime = Math.floor((endTime -JSON.parse(startTime))/1000);
if(elapsedTime > 5){
alert("5 min is completed.");
// Clear app data
}
console.log('Time elapsed'+ elapsedTime);
}
} catch (error) {
// console.log('Something went wrong', error);
}
}Problem:每当连接状态发生变化时,startTimer和checkElapsed都会调用。这个代码有什么问题。
如果我将给定的代码修改为:
state = {
isConnected: true
};
componentDidMount() {
this.unsubscribeFromNetInfo = NetInfo.addEventListener((state) => {
this.handleConnection(state.isConnected);
});
}
componentWillUnmount() {
this.unsubscribeFromNetInfo();
}
handleConnection = (isConnected) => {
console.log(isConnected);
this.setState({ isConnected });
};EventListener多次调用状态,经常发生真、真、假。
发布于 2020-03-05 11:21:37
现在,您正在错误地处理NetInfo订阅,根据https://github.com/react-native-community/react-native-netinfo#usage
你要做的是:
componentDidMount() {
this.unsubscribeFromNetInfo = NetInfo.addEventListener(state => {
this.handleConnection(state.isConnected);
});
}
componentWillUnmount() {
this.unsubscribeFromNetInfo();
}此外,如果要检查5分钟,请使用:
if (elapsedTime > 5 * 60)作为你的皈依
Math.floor((endTime - JSON.parse(startTime)) / 1000)将其转换为秒而不是分钟。
在当前状态下,应用程序将触发几乎所有东西,因为代码只检查5秒。
否则,您实现的逻辑应该是工作的:)
https://stackoverflow.com/questions/60543511
复制相似问题