首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果断开与互联网的连接超过5分钟,则清除应用程序数据。

如果断开与互联网的连接超过5分钟,则清除应用程序数据。
EN

Stack Overflow用户
提问于 2020-03-05 10:42:12
回答 1查看 521关注 0票数 0

如果我的应用程序与互联网断开超过5分钟,我想清除本地应用程序的数据。

我正在使用react本机NetInfo检查网络连接状态。节省应用程序断开连接的时间,并检查它何时将重新连接到internet。如果间隔超过5分钟,那么我想清除应用程序数据。

我的守则是:

代码语言:javascript
复制
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都会调用。这个代码有什么问题。

如果我将给定的代码修改为:

代码语言:javascript
复制
    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多次调用状态,经常发生真、真、假。

EN

回答 1

Stack Overflow用户

发布于 2020-03-05 11:21:37

现在,您正在错误地处理NetInfo订阅,根据https://github.com/react-native-community/react-native-netinfo#usage

你要做的是:

代码语言:javascript
复制
componentDidMount() {
    this.unsubscribeFromNetInfo = NetInfo.addEventListener(state => {
        this.handleConnection(state.isConnected);
    });
}

componentWillUnmount() {
    this.unsubscribeFromNetInfo();
}

此外,如果要检查5分钟,请使用:

代码语言:javascript
复制
if (elapsedTime > 5 * 60)

作为你的皈依

代码语言:javascript
复制
Math.floor((endTime - JSON.parse(startTime)) / 1000)

将其转换为秒而不是分钟。

在当前状态下,应用程序将触发几乎所有东西,因为代码只检查5秒。

否则,您实现的逻辑应该是工作的:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60543511

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档