我正在尝试使用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});
}
}
}
答案 0 :(得分:0)
看看Later.js。您可以设置每分钟触发的计划
const schedule = later.parse.text('every 1 mins');
later.date.localTime();
later.setTimeout(<your function>, schedule);
答案 1 :(得分:0)
也许这里的这个问题可以帮助人们: https://stackoverflow.com/a/49886834/12056841
<块引用>这里无法修复此错误,我们只能解决错误,有可用的解决方法可以禁用警告