无法清除 setInterval

Can't clear the setInterval

我想清除单击停止按钮时的间隔,似乎 clearInterval 没有按预期在那里工作。当 handleStop 函数被触发或当 handleReset id 被触发时定时器不会停止

这是我正在尝试做的事情:

import React from "react"
import useApp from "../App"
import Interact from "./Interact";

const Timer = () => {
    
    let timer;
    const {millisec , setMillisec , sec , setSec , min , setMin , hr , setHr} = useApp();
    const handleStart = () => {
     timer =  setInterval(() => {
          setMillisec((prev) => {
            if (prev === 100) {
              setSec((prevB) =>{
                if(prevB === 60){
                    setMin(prevC => {
                        if(prevC === 60){
                            setHr(prevD => prevD + 1)
                            return 0
                        } 
                        return prevC + 1
                    })
                    return 0
                }
             return prevB + 1
            });
              return 0;
            }
            return prev + 1;
          });
        }, 10);

       

      };
    const handleStop = () => {
        clearInterval(timer)
    }
    
    const handleReset = () => {
            clearInterval(timer)
        setMillisec(0)
        setSec(0)
        setMin(0)
        setHr(0)
    }

    return(
        <>
            <div className="parent">
                <div className="main">
                    <h1 className="heading">Stop Watch</h1>
                    <div className="timer">
                    <div className ="hour">{hr}</div>
                    <div className ="min">{min}</div>
                    <div className ="sec">{sec}</div>
                    <div className ="millisec">{millisec}</div>
                    </div>
                    <Interact handleStart = {handleStart} 
                              handleStop = {handleStop} 
                              handleReset ={handleReset}
                              />
                </div>
            </div>
           
            
        </>
    )
}
export default Timer

在需要中断时将 setInterval() 传递给 clearInterval()。

变量 timer 每次 Timer 组件渲染时重新声明。因此,setInterval 引用被重置。

你可以在全局范围内声明定时器,比如

...
import Interact from "./Interact";

let timer;
const Timer = () => {    
    const {millisec , setMillisec , sec , setSec , min , setMin , hr , setHr} = useApp();
    const handleStart = () => {
...

或者也可以使用react-hooks来维护setInterwal引用。喜欢 this