【发布时间】:2020-03-29 09:50:41
【问题描述】:
我正在尝试在 react 中使用钩子实现 5 秒倒计时。 在其他答案中,解决方案是使用 React.useEffect 实现 setInterval,但我想让最终用户使用按钮触发倒计时。 然后,在倒计时结束时,执行一个函数。
我管理了显示计时器,但是当计时器为 0 时我没有设法执行函数。 在以下情况下,console.log 不会被触发。
function Test(){
const [timeLeft, setTimeLeft] = useState(null);
useEffect(() => {
// exit early when we reach 0
if (!timeLeft) return;
if(timeLeft===0){
console.log("TIME LEFT IS 0");
setTimeLeft(null)
}
// save intervalId to clear the interval when the
// component re-renders
const intervalId = setInterval(() => {
setTimeLeft(timeLeft - 1);
}, 1000);
// clear interval on re-render to avoid memory leaks
return () => clearInterval(intervalId);
// add timeLeft as a dependency to re-rerun the effect
// when we update it
}, [timeLeft]);
return (
<React.Fragment>
{timeLeft}
<Button onClick={()=>setTimeLeft(5)} className={classes.button}>
TEST
</Button>
</React.Fragment>
})
}
【问题讨论】:
-
向我们展示您的尝试。
-
@trixn 编辑了问题
标签: javascript reactjs react-hooks countdown