use*_*258 2 javascript timer reactjs
我想设置倒计时器从 00:00 开始,每 5 分钟重复一次。(例如:当时间为 00:05 时,计时器倒计时 5 分钟,直到 00:10,并在 00:10 再次倒计时 5 分钟,依此类推)
这是我现在的代码:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
minutes: 5,
seconds: 0
};
}
...............
componentDidMount() {
this.getData();
this.myInterval = setInterval(() => {
const { seconds, minutes } = this.state
if (seconds > 0) {
this.setState(({ seconds }) => ({
seconds: seconds - 1
}))
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(this.myInterval)
} else {
this.setState(({ minutes }) => ({
minutes: minutes - 1,
seconds: 59
}))
}
}
}, 1000)
}
...........
return (
<p>Countdown : {this.state.minutes}:{this.state.seconds < 10 ? `0${this.state.seconds}` : this.state.seconds} </p>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我应该在哪里更改或添加以使倒计时从 00:00 开始并每 5 分钟重复一次。有人可以帮助我吗?
使用setInterval会让我头疼,弄清楚每次在反应重新渲染过程之后发生了什么,并且越来越多的间隔被添加到事件循环中,我建议使用setTimeoutcomponentDidUpdate 方法来更新状态并在最后进行清理,或者使用使生活更轻松
这是一个带有钩子的解决方案
function App() {
const [seconds, setSeconds] = useState(0)
const [minutes, setMinutes] = useState(5)
function updateTime() {
if (minutes == 0 && seconds == 0) {
//reset
setSeconds(0);
setMinutes(5);
}
else {
if (seconds == 0) {
setMinutes(minutes => minutes - 1);
setSeconds(59);
} else {
setSeconds(seconds => seconds - 1);
}
}
}
useEffect(() => {
// use set timeout and be confident because updateTime will cause rerender
// rerender mean re call this effect => then it will be similar to how setinterval works
// but with easy to understand logic
const token = setTimeout(updateTime, 1000)
return function cleanUp() {
clearTimeout(token);
}
})
return (<p>
time: {minutes}:{seconds}
</p>);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12113 次 |
| 最近记录: |