Javascript setInterval和setTimeout均不适用于本机ES6

Javascript setInterval和setTimeout均不适用于本机ES6,javascript,react-native,Javascript,React Native,我试图让一个基本的计时器进入react native,但它不起作用。控制台中没有错误。它只是简单地忽略了setInterval。我阅读了ES6的问题(不受支持)。那么,如果您只想使用一个基本的setIntervaltimer?,又该怎么办呢?因为它不能以这里所示的最简单的形式工作 import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; class HelloWorld

我试图让一个基本的计时器进入react native,但它不起作用。控制台中没有错误。它只是简单地忽略了
setInterval
。我阅读了ES6的问题(不受支持)。那么,如果您只想使用一个基本的
setInterval
timer?,又该怎么办呢?因为它不能以这里所示的最简单的形式工作

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);
import React,{Component}来自'React';
从“react native”导入{AppRegistry,Text};
类HelloWorldApp扩展了组件{
componentDidMount(){
console.log('COMPONENTDIDMOUNT')

//this.timer=您可以尝试此模块,因为react native中的计时器对ES6来说没有什么困难。

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

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

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

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


参考资料:

你在控制台中看到什么了吗?
我将使用this.timer=this.timer(绑定)。这;
…为什么?这让我不明白,但我对代码中的注释进行了评论,并指出我怀疑问题在于您的setInterval回调不起作用。让我直说吧-您在控制台上获得
COMPONENTDIDMOUNT
COMPONENTWILLUNMOUNT
,但您从未获得
I不要泄漏!
在控制台上-即使前两次之间的间隔超过5秒?我已将您的代码缩减到最低限度,对于使用react navigation Component WillUnmount()的用户,它可以正常工作(在两个位置使用this.timer后)未调用。在这种情况下如何清除间隔?@HarshitAgrawal,您可以使用导航事件模糊,当屏幕失去焦点时将调用它。您能否共享示例代码的任何代码片段或url?如何实现这一点?