setInterval 和 setTimeout 都不起作用反应原生 ES6 [英] Neither setInterval nor setTimeout works react-native ES6
本文介绍了setInterval 和 setTimeout 都不起作用反应原生 ES6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 react-native 中使用一个基本的计时器,但它不起作用.我在控制台中没有收到任何错误.它只是简单地忽略 setInterval
.我阅读了 ES6 的
解决方案
您需要将时间保存为实例变量并在组件卸载时清除它.示例:
componentDidMount() {this._interval = setInterval(() => {//你的代码}, 5000);}componentWillUnmount() {clearInterval(this._interval);}
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);
}
这篇关于setInterval 和 setTimeout 都不起作用反应原生 ES6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文