首页 > 解决方案 > 尝试实现倒计时时反应过多的重新渲染

问题描述

如果您能帮助我,我将不胜感激。所以基本上我试图在反应应用程序上显示倒计时。但是,我收到了太多渲染发生的错误。我相信这是因为我更新了 useEffect 钩子本身的计数器,但我在网上看到了做同样事情的例子(据他们说,它有效)


 const [question, setQuestion] = useState([]);
  const [counter, setCounter] = useState(60);

  if (question === []) {
    //make API request
        setQuestion(apiResponse) //confirmed this works
  } else {
    //endingTime and currentTime are variables with the correct values (confirmed this)
    setCounter(endingTime - currentTime);
  }

  React.useEffect(() => {
    const timer = counter > 0 && setInterval(() => setCounter(counter - 1), 1000);
    if (counter === 0) setCounter('Time is Up');
    return () => clearInterval(timer);
  }, [counter]);

标签: reactjsuse-effect

解决方案


推荐阅读