【发布时间】:2021-05-18 01:07:40
【问题描述】:
我有一些逻辑来处理我的 react-native 应用程序中的计时器。现在我正在观察一些奇怪的行为。当我第一次启动计时器时,它会按预期运行。当我单击stop 时,它会显示最后一个值。然后,当我再次单击开始时,它应该获取最后一个值并继续递增。但是,在重新启动时发生的情况是,值会提前几秒钟,然后从那里递增,我不知道为什么。
有四个主要组件:_startTimer()、_stopTimer()、calculateDuration() 和 continueTimer()。
问题似乎发生在 _continueTimer() 运行时,特别是在从该函数中调用 _calculateDuration() 时。
constructor(props) {
super(props);
this.timer = null;
this.state = {
duration: props?.duration || '00:00:00',
startTime: props?.started ? moment(props.started).format('YYYY-MM-DD HH:mm:ss') : null,
stopTime: props?.stopped ? moment(props.stopped).format('YYYY-MM-DD HH:mm:ss') : null,
};
}
async _startTimer() {
if (this.timer) clearInterval(this.timer);
let stateUpdate = {
stopTime: null,
};
if (!this.state.startTime) {
const newStartTime = moment(Date.serverTime() || Date.now());
stateUpdate.startTime = newStartTime.format('YYYY-MM-DD HH:mm:ss');
}
this.setState(stateUpdate, () => {
this.timer = setInterval(async () => {
const newDuration = this._calculateDuration();
this.setState({
duration: newDuration,
});
}, 1000);
if (this.props.onChange) this.props.onChange(this.state);
});
};
_stopTimer() {
return new Promise((resolve) => {
if (this.timer) clearInterval(this.timer);
const newStopTime = moment(Date.serverTime());
this.setState({
stopTime: newStopTime.format('YYYY-MM-DD HH:mm:ss'),
}, async () => {
if (this.props.onChange) await this.props.onChange(this.state);
});
});
};
_calculateDuration() {
const startTime = moment(this.state.startTime).valueOf();
const stopTime = this.state.stopTime ? moment(this.state.stopTime).valueOf() : moment().valueOf();
const duration = moment.duration(stopTime - startTime).asMilliseconds();
const durationFormatted = moment.utc(duration).format('HH:mm:ss');
return durationFormatted;
};
async _continueTimer() {
if (this.timer) clearInterval(this.timer);
this.setState({
stopTime: null,
}, () => {
this.timer = setInterval(async () => {
const newDuration = this._calculateDuration();
this.setState({
duration: newDuration,
});
}, 1000);
if (this.props.onChange) this.props.onChange(this.state);
});
};
【问题讨论】:
-
这行得通吗?如果可以,您可以标记为已回答,我很感兴趣
标签: reactjs react-native