设置倒数计时器 React JS [英] set countdown timer React JS
问题描述
我想设置倒数计时器从 00:00 开始并每 5 分钟重复一次.(例如:当时间是 00:05 时,计时器倒计时 5 分钟,直到 00:10,在 00:10 再次倒计时 5 分钟,并且等等)
i want to set countdown timer start at 00:00 and repeated every 5 minute.(example: when time is 00:05 timer is countdown 5 minutes until 00:10, and in 00:10 countdown 5 minute again, and so on)
这是我现在的代码:
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>
);
}
}
我应该在哪里更改或添加以使倒计时从 00:00 开始并每 5 分钟重复一次.有人可以帮我吗?
where i should change or add to make this countdown start at 00:00 and repeated every 5 minute. anyone can help me?
推荐答案
使用 setInterval
会让我头疼,搞清楚每次在反应重新渲染过程后发生了什么,并且添加了越来越多的间隔在事件循环中,我建议使用 setTimeout
和 componentDidUpdate 方法来更新状态并在最后清理或使用钩子使生活更轻松
using setInterval
will make me a headache figuring out what happened every time after a react rerender process with more and more interval being added to the event loop, I would recommend using setTimeout
with componentDidUpdate method to udpate state and clean up at the end or using hooks which made life easier
这是一个带钩子的解决方案
here is a solution with hooks
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>);
}
这篇关于设置倒数计时器 React JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!