更新的状态值不会在反应中的函数内部更新

沙提什·德赛

反应状态更新值显示在使用效果中,但在函数内部仅显示旧值。

const [counter, setCounter] = useState(0);

我正在尝试更新设置间隔函数内的计数器值

 const handleIncrease = () => {
clearInterval(intervalval);
if (counter < 10) {
  let increment = setInterval(() => {
    console.log("isCounterContinue@handleIncrease", counter);
    setCounter((prev) => prev + 1);
  }, 1000);
  setIntervalval(increment);
}

}; 显示内部 useEffect 更新值。但内部函数handleIncrease只显示旧值基本上,我试图做计数器值超过30时不增加。

代码链接:https : //codesandbox.io/s/bold-cdn-zzbs2?file=/ src/ App.js

德鲁里斯

handleIncrease仅在单击按钮时使用当前状态调用。单击处理程序中没有任何可更新的内容。我认为您真正想要的是访问counter间隔回调中的更新状态,每秒“滴答”一次。或者更准确地说,响应isCounterContinue状态切换 false 以在达到限制时停止间隔。

使用 ref 来保存对间隔计时器的引用,并使用它来设置/清除,而不是在外壳中过时的状态。

const Timer = () => {
  const [counter, setCounter] = useState(0);
  const intervalRef = useRef();

  useEffect(() => {
    console.log({ counter });
    if (counter >= 5) {
      clearInterval(intervalRef.current);
    }
  }, [counter]);

  const handleIncrease = () => {
    clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      setCounter((prev) => prev + 1);
    }, 1000);
  };

  const handleDecrease = () => {
    clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      setCounter((prev) => prev - 1);
    }, 1000);
  };

  const handleStop = () => {
    clearInterval(intervalRef.current);
  };

  return (
    <>
      <div>{counter}</div>
      <div>
        <button onClick={handleDecrease}>Decrease</button>
        <button onClick={handleStop}>Stop</button>
        <button onClick={handleIncrease}>Increase</button>
      </div>
    </>
  );
};

建议

除了添加到计数中的内容之外,递增/递减处理程序基本相同。使用柯里化函数通过关闭递增值来处理这两种情况。由于“停止”处理程序共享清除间隔的逻辑,因此使用0假值这一事实并且仅重新启动间隔计时器以获取真值(即非零)数值,并对所有三个按钮使用一个处理程序。

const handleIncrease = (val) => () => {
  clearInterval(intervalRef.current);
  if (val) {
    intervalRef.current = setInterval(() => {
      setCounter((prev) => prev + val);
    }, 1000);
  }
};

...

<button onClick={handleIncrease(-1)}>Decrease</button>
<button onClick={handleIncrease(0)}>Stop</button>
<button onClick={handleIncrease(1)}>Increase</button>

编辑updated-state-value-are-not-updated-inside-function-in-react

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章