简体   繁体   中英

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. I get no errors in the console. It just simply ignores the setInterval . I read the TimerMixin issue with ES6 (not supported). 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...

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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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