React-带钩的5秒钟倒计时

问题描述 投票:-2回答:1

我正在尝试使用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>
 })
}
javascript reactjs react-hooks countdown
1个回答
-1
投票
function Test(){ const [timeLeft, setTimeLeft] = useState(null); useEffect(() => { if(timeLeft===0){ console.log("TIME LEFT IS 0"); setTimeLeft(null) } // exit early when we reach 0 if (!timeLeft) return; // 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> }) }

0
投票

我的错误。0将触发useEffect中的返回。我只需要把支票移到它上面:

function Test(){
   const [timeLeft, setTimeLeft] = useState(null);

useEffect(() => {
    if(timeLeft===0){
       console.log("TIME LEFT IS 0");
       setTimeLeft(null)
    }

    // exit early when we reach 0
    if (!timeLeft) return;

    // 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>
 })
}
© www.soinside.com 2019 - 2024. All rights reserved.