在 React 中使用 setState 时,setInterval 不能被 clearInterval 停止

setInterval can't be stopped by clearInterval when use setState in React

  const handleClick = () => {
    setState({ ...state, on: !state.on });
    let tog = state.on;
    console.log("first" + tog);
    const interval = setInterval(() => {
      if (tog) {
        console.log(tog);
      } else clearInterval(interval);
    }, 1000);
  };

enter image description here 即使是假的,这个也无法停止; 但是,如果我不使用状态,则更改为变量就不会发生, 这对我来说太奇怪了,我需要一些帮助;

let flag = true;
  const handleClick = () => {
    flag = !flag;
    console.log("first" + flag);
   const interval = setInterval(()=>{
     if(flag){
       console.log(flag);
     }else(clearInterval(interval))
   },1000)
  };

React 将在每个 re-renders 上创建新的 handleClick,并且会有不同的 setIntervals,

const intvl = useRef(null);

const handleClick = () => {
    intvl.current = setInterval(() => { //now interval is not changing on every fn recreation
        .....

   clearInterval(intvl.current);
}

check this one

你应该使用 Effect 来处理间隔,像这样:

  useEffect(() => {
    let intervalId
    if (state.on) { 
      intervalId = setInterval(() => {
        console.log(state.on)
      }, 1000)
      return () => clearInterval(intervalId)
    }
  }, [state.on])

  const handleClick = () => {
    setState({ ...state, on: !state.on });
  };

working code