【问题标题】:React - 5 seconds countdown with hooksReact - 带钩子的 5 秒倒计时
【发布时间】: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


【解决方案1】:

我的错。 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>
 })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2020-06-30
    • 2011-08-04
    • 2021-03-02
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    相关资源
    最近更新 更多