React - 用钩子倒计时 5 秒

Fra*_*nti 2 javascript countdown reactjs react-hooks

我正在尝试在 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>
 })
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*nti 5

我的错。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>
 })
}
Run Code Online (Sandbox Code Playgroud)