【问题标题】:Neither setInterval nor setTimeout works react-native ES6setInterval 和 setTimeout 都不起作用 react-native ES6
【发布时间】:2016-08-10 00:39:14
【问题描述】:

我正在尝试在 react-native 中设置一个基本计时器,但它不起作用。我在控制台中没有错误。它只是简单地忽略了setInterval。我阅读了 ES6 的 TimerMixin 问题(不支持)。那么,如果您只想使用基本的 setInterval 计时器,还有什么选择?因为它根本无法以此处显示的最简单形式工作...

import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';

class HelloWorldApp extends Component {

componentDidMount() {
      console.log('COMPONENTDIDMOUNT')
   //this.timer=     <--//This doesn't work either 
     var timer = setInterval(() => {
      console.log('I do not leak!');
    }, 5000);
  }
componentWillUnmount() {
    console.log('COMPONENTWILLUNMOUNT')
  clearInterval(timer); 
}
  render() {
    return (
      <Text>Hello world!</Text>
    );
  }
}

AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);

【问题讨论】:

  • 那么您在控制台中看到什么了吗?
  • I will use this.timer = this.timer(bind).this; ... 为什么?这没有任何意义
  • 我明白,但我在评论代码中的评论,并指出我怀疑问题是您的 setInterval 回调不起作用
  • 让我直截了当地说 - 你在控制台上得到 COMPONENTDIDMOUNTCOMPONENTWILLUNMOUNT,但在控制台上你永远不会得到 I do not leak! - 即使前两者之间的间隔超过 5 秒?
  • 我已将您的代码缩减到最低限度,并且工作正常(一旦您在两个地方都使用 this.timer)

标签: javascript react-native


【解决方案1】:

您需要将时间保存为实例变量并在组件卸载时将其清除。示例:

componentDidMount() {
  this._interval = setInterval(() => {
    // Your code
  }, 5000);
}

componentWillUnmount() {
  clearInterval(this._interval);
}

【讨论】:

  • 对于那些使用 react-navigation 的组件WillUnmount() 不会被调用。在这种情况下如何清除Interval?
  • @HarshitAgrawal ,您可以使用 Navigation 事件 blur 将在屏幕失焦时调用。
  • 你能分享任何代码sn-p或任何示例代码的url如何实现这一点吗?
【解决方案2】:

你可以试试这个模块,因为 react-native 中的 Timers 对 ES6 来说没什么痛苦。 https://github.com/fractaltech/react-native-timer

【讨论】:

    【解决方案3】:

    根据您的屏幕截图,它清楚地提到您的设备和调试器之间存在时间差。请同步两台设备以使用时间服务器(自动设置日期和时间),问题将得到解决。

    参考:https://github.com/facebook/react-native/issues/9436

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      相关资源
      最近更新 更多