【发布时间】:2017-12-07 00:43:36
【问题描述】:
我正在尝试使用 React Native 创建一个需要在屏幕上显示时钟的应用程序(只需几分钟即可正确更新,而不是几秒钟)。该应用程序可能会在屏幕上(可见)数分钟。
有没有正确的方法来做到这一点,到目前为止,我尝试过的每一种方法都会出现“长时间设置计时器,即多分钟,是 Android 上的性能和正确性问题......”。
我怎样才能完成一个简单的时钟,正确且对电池等影响最小。
时钟工作正常,我只是收到警告。我尝试了各种方法,包括常规的 setTimeout/Interval 和 this.setTimeout,还有 react-native-background-timer。
我也只需要在此屏幕重新出现时更新时钟,因此我取消了 componentDidUnmount 上的计时器。时钟只需要按分钟更新,而不是按秒更新,并且不需要 100% 准确,即在分钟更新正常之前有一点延迟。
谢谢!
代码:
import React, {Component} from 'react';
import {View, Image, AppState} from 'react-native';
import {Text} from 'react-native';
import Styles from '../../styles/Styles';
import BackgroundTimer from 'react-native-background-timer';
/*
Digital Clock
*/
export default class UIDigitalClock extends Component {
// Render -----------------
render() {
var label = this.formatAMPM(this.state.time);
return (
<Text style={[Styles.h0,{fontSize:80,opacity:0.7}]}>{label}</Text>
);
}
formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes;
return strTime;
}
//--------------------------------
constructor(props) {
super(props);
this.state = {
time: new Date()
}
}
timer = null;
componentWillMount() {
AppState.addEventListener('change', this.handleAppStateChange);
console.log('Digital Clock - Mount - Start');
this.startTimer();
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
this.stopTimer();
}
startTimer() {
return;
if (this.timer>0) return; // Already started
this.timer = BackgroundTimer.setInterval(() => {
// this will be executed every 200 ms
// even when app is the the background
this.updateTime();
}, 1000);
}
stopTimer() {
console.log("Digital Clock - stop ");
if (this.timer>0) {
BackgroundTimer.clearInterval(this.timer);
this.timer = -1;
}
}
handleAppStateChange = (appState) => {
console.log("Digital Clock app state: "+appState);
if (appState=='background') {
console.log('Digital Clock - App in Background - Stop');
this.stopTimer();
} else if (appState=='active') {
console.log('Digital Clock - App is Active - Start');
this.startTimer();
}
}
updateTime() {
let time = this.state.time;
let newTime = new Date();
// TODO - check if the app is in the foreground
console.log('Digital Clock - Tic ');
// Only update the render when the time changes...
if (!time || (time.getMinutes() != newTime.getMinutes() || time.getHours() != newTime.getHours())) {
console.log('Digital Clock - Time changed (mins/hours) - updating...');
this.setState({time: newTime});
}
}
}
【问题讨论】:
标签: react-native