我正在React中完成Timer项目。这是我的计时器组件的代码:
import React, {Component} from 'react';
class Timer extends Component {
constructor(props){
super(props);
this.state = {
count: 0,
pause: true,
clock: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0
};
}
componentDidMount() {
this.countTimers();
}
countTimers = () => {
let counter = setInterval(() => {
if (!this.state.pause) {
this.setState({
count: this.state.count + 1,
days: Math.floor(this.state.count / (1000 * 60 * 60 * 24)),
hours: Math.floor((this.state.count % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes: Math.floor((this.state.count % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((this.state.count % (1000 * 60)) / 1000)
})
console.log(this.state.seconds);
}
}
, 1000);
}
startHandler = () => {
this.setState({
pause: false
})
}
pauseHandler = () => {
this.setState({
pause: true
})
}
render () {
return (
<div>
<p>{'Time spent on this site'}</p>
<span className="days">{this.state.days}:</span>
<span className="hours">{this.state.hours}:</span>
<span className="minutes">{this.state.minutes}:</span>
<span className="seconds">{this.state.seconds} </span>
<button id="start" onClick={this.startHandler}>START</button>
<span>{this.state.count}</span>
<button id="pause" onClick={this.pauseHandler}>PAUSE</button>
</div>
);
}
}
export default Timer;
一切都很好,但我没有收到要从公式中获取的天,小时,分钟和秒的值:
days: Math.floor(this.state.count / (1000 * 60 * 60 * 24)),
hours: Math.floor((this.state.count % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes: Math.floor((this.state.count % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((this.state.count % (1000 * 60)) / 1000)
需要明确的是,我没有使用date对象来获取任何值,而只是通过设置1000毫秒的间隔来使用setInterval函数来增加秒的值。有谁知道如何解决这个问题?