我正在尝试使用以下代码构建Pomodoro时钟,但是,当时钟到达0:00时,我陷入了困境,标题和对应的时间不在“ Session”和“ Break”之间切换。当我记录currentTimer
状态变量时,我看到它固定在两个变量上,但是当代码达到预期的时钟为0时,它并没有在另一个变量之间变化。为什么?所有这些逻辑都发生在handlePlayPause
方法中。
import React from 'react';
import SetTimer from './components/SetTimer';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
// this.loop = undefined;
this.handlePlayPause = this.handlePlayPause.bind(this);
}
state = {
breakCount: 1,
sessionCount: 1,
clockCount: 3,
currentTimer: 'Session',
isPlaying: false,
loop: undefined,
};
handlePlayPause() {
const { isPlaying, breakCount, sessionCount, currentTimer } = this.state;
console.log(isPlaying);
if (isPlaying) {
//if the time is playing and we press this button, then we need to puase or clear the playing intervals
clearInterval(this.loop);
this.setState({ isPlaying: false });
} else {
this.setState({ isPlaying: true });
this.loop = setInterval(() => {
const { clockCount } = this.state;
if (clockCount === 0) {
console.log(currentTimer);
this.setState({
currentTimer: currentTimer === 'Session' ? 'Break' : 'Session',
clockCount: currentTimer === 'Session' ? 3 : 4,
});
} else {
this.setState({ clockCount: clockCount - 1 });
}
}, 1000);
}
}
componentWillUnmount() {
clearInterval(this.loop);
}
convertTime = (count) => {
const minutes = Math.floor(count / 60);
let seconds = count % 60;
seconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
return `${minutes}:${seconds}`;
};
render() {
const { breakCount, sessionCount, clockCount, currentTimer } = this.state;
const breakProps = {
title: 'Break Length',
count: breakCount,
handleDecrease: this.handleBreakDecrease,
handleIncrease: this.handleBreakIncrease,
};
const sessionProps = {
title: 'Session Length',
count: sessionCount,
handleDecrease: this.handleSessionDecrease,
handleIncrease: this.handleSessionIncrease,
};
return (
<div>
<div className='flex'>
<SetTimer {...breakProps} />
<SetTimer {...sessionProps} />
</div>
<div className='clock-container'>
<h1>{currentTimer}</h1>
<span>{this.convertTime(clockCount)}</span>
<div className='flex'>
<button onClick={this.handlePlayPause}>
{this.state.isPlaying ? (
<i className={`fas fa-pause`}></i>
) : (
<i className='fas fa-play'></i>
)}
</button>
<button onClick={this.handleReset}>
<i className='fas fa-sync-alt'></i>
</button>
</div>
</div>
</div>
);
}
}
export default App;