setInterval和setTimeout都不能反应原生ES6

时间:2016-08-10 00:39:14

标签: javascript 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);

enter image description here enter image description here

3 个答案:

答案 0 :(得分:15)

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

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

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

答案 1 :(得分:0)

你可以尝试这个模块,因为在本机反应中,定时器对于ES6来说几乎没有什么痛苦。 https://github.com/fractaltech/react-native-timer

答案 2 :(得分:0)

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

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

相关问题