Javascript setInterval 和 setTimeout 都不起作用反应原生 ES6
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38862512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Neither setInterval nor setTimeout works react-native ES6
提问by cube
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 TimerMixinissue 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...
我正在尝试让一个基本的计时器在本机中运行,但它不起作用。我在控制台中没有收到任何错误。它只是简单地忽略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);
回答by Jeremie
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);
}
回答by Vikram Belde
You can try this module as Timers in react-native is little pain with ES6. https://github.com/fractaltech/react-native-timer
你可以试试这个模块,因为 React-native 中的 Timers 对 ES6 来说并不痛苦。 https://github.com/fractaltech/react-native-timer
回答by Ashok
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