简体   繁体   English

setInterval 和 setTimeout 都不起作用 react-native ES6

[英]Neither setInterval nor setTimeout works react-native ES6

I'm trying to get a basic timer going in react-native, but it's not working.我正在尝试在 react-native 中安装一个基本计时器,但它不起作用。 I get no errors in the console.我在控制台中没有错误。 It just simply ignores the setInterval .它只是简单地忽略了setInterval I read the TimerMixin issue with ES6 (not supported).我阅读了 ES6 的TimerMixin问题(不支持)。 So what is the alternative if you want to use just a basic setInterval timer?, as it simply does not work in its simplest form shown here...那么,如果您只想使用基本的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);

在此处输入图像描述 在此处输入图像描述

You need to save the time as an instance variable and clear it on component unmount.您需要将时间保存为实例变量并在组件卸载时清除它。 Example:示例:

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

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

You can try this module as Timers in react-native is little pain with ES6.你可以试试这个模块,因为 React-native 中的 Timers 对 ES6 来说并不痛苦。 https://github.com/fractaltech/react-native-timer https://github.com/fractaltech/react-native-timer

As per your screenshot, it clearly mentions there is a time difference between your device and debugger.根据您的屏幕截图,它清楚地提到您的设备和调试器之间存在时间差异。 Please sync both devices to use a time server (automatically set date and time) and issue will be resolved.请同步两个设备以使用时间服务器(自动设置日期和时间),问题将得到解决。

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

 const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM