[英]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.