尝试在 React JS 中执行计数器时超出最大调用堆栈大小

maximum call stack size exceed when try to do a counter in react js

尝试在 React js 中执行计数器时,超出最大调用堆栈大小。 我正在使用一个功能组件来创建一个计数器。那将从0开始,每次增加10,直到达到最大限制。 这是我的代码

const [initialCount, setInitialCount] = useState(0);
useEffect(() => {
  const handleScoreAnimate = () => {
    if (initialCount >= maxLimit) {
      setInitialCount(maxLimit);
    } else {
      setInitialCount(initialCount + 10);
      handleScoreAnimate();
    }
  }
  if (initialCount === 0) {
    handleScoreAnimate();
  }
}, [initialCount]);

错误是由于在 useEffect 中递归调用 handleScoreAnimate 函数造成的。

你可能会得到更好的解决方案,但你可以利用 setTimeout 来实现,

useEffect(() => {

   const timer = setTimeout(()=>{
      setInitialCount(c => c >= maxLimit ? maxLimit : c + 10)
   },1000)  //timeout can be adjusted according to your need

   //This is to clear the timeout when component unmounts
   return () => clearTimeout(timer);

}, [initialCount]);

Demo