setInterval和setTimeout都不能反应原生ES6

cub*_*ube 13 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);
Run Code Online (Sandbox Code Playgroud)

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

小智 24

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

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

componentWillUnmount() {
  clearInterval(this._interval);
}
Run Code Online (Sandbox Code Playgroud)


小智 0

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