[英]Neither setInterval nor setTimeout works react-native ES6
我正在尝试在 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);
您需要将时间保存为实例变量并在组件卸载时清除它。 示例:
componentDidMount() {
this._interval = setInterval(() => {
// Your code
}, 5000);
}
componentWillUnmount() {
clearInterval(this._interval);
}
你可以试试这个模块,因为 React-native 中的 Timers 对 ES6 来说并不痛苦。 https://github.com/fractaltech/react-native-timer
根据您的屏幕截图,它清楚地提到您的设备和调试器之间存在时间差异。 请同步两个设备以使用时间服务器(自动设置日期和时间),问题将得到解决。
const interval = setInterval(() => {
console.log('This will run every second!');
}, 1000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.