目录

一、问题描述

二、解决方案

方案一,使用函数式更新

方案二,使用 useRef 保存最新值


一、问题描述

在 React 中,当在 setInterval或setTimeout 中使用 setState 时,经常会遇到状态不是最新值的问题。这是因为闭包导致的,setInterval 回调函数捕获的是初始状态值。

二、解决方案

方案一,使用函数式更新
useEffect(() => {
  const interval = setInterval(() => {
    // 使用函数式更新,获取最新的状态
    setCount(prevCount => prevCount + 1);
  }, 1000);
  
  return () => clearInterval(interval);
}, []);
方案二,使用 useRef 保存最新值
import { useState, useEffect, useRef } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const countRef = useRef(count);

  // 保持 ref 与状态同步
  useEffect(() => {
    countRef.current = count;
  }, [count]);

  useEffect(() => {
    const interval = setInterval(() => {
      // 通过 ref 获取最新值
      setCount(countRef.current + 1);
    }, 1000);
    
    return () => clearInterval(interval);
  }, []);

  return <div>计数: {count}</div>;
}

以上解决方案可解此问题。

更多推荐