我如何使setState在setInterval中工作? (当前工作正常)

问题描述 投票:0回答:2
    function func(){
      const [time, setTime] = useState(10);
      var timeRemaining = 10;
      const myInterval = setInterval(() => {
                        if (timeRemaining > 0) {
                            timeRemaining = timeRemaining - 1;
                            setTime(timeRemaining);
                        } else { clearInterval(myInterval) }
                    }, 1000);
       return <div>{time}</div>
     }

如果我这样写的话,它要感谢普通变量“ timeRemaining”,但是,如果我写了:

     const myInterval = setInterval(() => {
                        if (time> 0) {
                            setTime(time-1);
                        } else { clearInterval(myInterval) }
                    }, 1000);

它将停止更新{time}

reactjs react-hooks setinterval setstate react-state
2个回答
1
投票

使用效果来控制间隔,使用ref保持对间隔计时器参考的引用,并使用功能状态更新以正确管理状态。

  • 效果1-间隔效果的设置(安装)和清除(卸载)
  • 效果2-时间到0时清除间隔

功能组件代码:

function App() {
  const timerRef = useRef(null);
  const [time, setTime] = useState(10);

  useEffect(() => {
    timerRef.current = setInterval(() => setTime(t => t - 1), 1000);
    return () => clearInterval(timerRef.current);
  }, []);

  useEffect(() => {
    if (time === 0) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  }, [time]);

  return <div>{time}</div>;
}

Edit focused-mendeleev-2cezr


0
投票

使用setTime的功能版本,尽管我建议您也将间隔放入useEffect中进行清理

  setTime((time) => {
    if (time > 0) {
      return time - 1;
    }
    clearInterval(myInterval);
    return time;
  });

具有useEffect:

function func() {
  const [time, setTime] = useState(10);
  var timeRemaining = 10;
  useEffect(() => {
    const myInterval = setInterval(() => {
      setTime((time) => {
        if (time > 0) {
          return time - 1;
        }
        clearInterval(myInterval);
        return time;
      });
    }, 1000);
    return () => {
      clearInterval(myInterval);
    };
  }, [input]);

  return <div>{timeRemaining}</div>;
}
© www.soinside.com 2019 - 2024. All rights reserved.