React中的clearInterval

Luc*_*cas 9 setinterval clearinterval reactjs

我是React的新手,我正在尝试创建一个带有启动和停止按钮的简单秒表.我正在撞墙,试图通过"停止"按钮上的onClick事件来清除InterInterval.我会为setInterval声明一个变量,然后使用clearInterval清除它.不幸的是它不起作用.有小费吗?先感谢您.

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {time:0}

    this.startHandler = this.startHandler.bind(this);
  }

  getSeconds(time){
    return `0${time%60}`.slice(-2);
  }

  getMinutes(time){
    return Math.floor(time/60);
  }

  startHandler() {
      setInterval(()=>{
      this.setState({time:this.state.time + 1});
    },1000)

  }

  stopHandler() {
    //HOW TO CLEAR INTERVAL HERE????
  }

  render () {
    return (
      <div>
        <h1>{this.getMinutes(this.state.time)}:{this.getSeconds(this.state.time)}</h1>
        <button onClick = {this.startHandler}>START</button>
        <button onClick = {this.stopHandler}>STOP</button>
        <button>RESET</button>
      </div>
    );
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

小智 24

您可以在没有依赖关系的情况下使用setTimeoutinside useEffect,因此它会在组件启动时调用一次,然后clearInterval在组件卸载时调用。

useEffect(() => {
    let intervalId = setInterval(executingFunction,1000)
    return(() => {
        clearInterval(intervalId)
    })
},[])
Run Code Online (Sandbox Code Playgroud)


Din*_*til 16

您可以为组件的状态添加间隔,并可以随时清除它.

componentDidMount(){
  let intervalId = setInterval(this.yourFunction, 1000)
  this.setState({ intervalId: intervalId })
}

componentWillUnmount(){
  clearInterval(this.state.intervalId)
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*rei 9

在您的startHandler函数中,您可以执行以下操作:

    this.myInterval = setInterval(()=>{
      this.setState({ time: this.state.time + 1 });
    }, 1000);
Run Code Online (Sandbox Code Playgroud)

并在stopInterval() ,你会怎么做clearInterval(this.myInterval);


Hen*_*ody 8

对于带钩子的 React 16.8+,您可以将 IntervalID 存储在 ref 值中(而不是状态中),因为当 IntervalID 更新时组件不需要重新渲染(并且始终可以访问最新的 IntervalID)。

这是一个例子:

function Timer() {
    const [time, setTime] = React.useState(0);
    const intervalIDRef = React.useRef(null);

    const startTimer = React.useCallback(() => {
        intervalIDRef.current = setInterval(() => {
            setTime(prev => prev + 1);
        }, 1000);
    }, []);

    const stopTimer = React.useCallback(() => {
        clearInterval(intervalIDRef.current);
        intervalIDRef.current = null;
    }, []);

    // resetTimer works similarly to stopTimer but also calls `setTime(0)`

    React.useEffect(() => {
        return () => clearInterval(intervalIDRef.current); // to clean up on unmount
    }, []);

    return (
        <div>
            <span>Time: {time}</span>
            <button onClick={startTimer}>START</button>
            <button onClick={stopTimer}>STOP</button>
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

请注意,对于像这样的计时器组件,最好通过引用相对于上次更新时间的当前时间(使用performance.nownew Date)来更新时间,而不是增加时间变量,因为它setInterval不提供记录时间的准确方法并且小随着时间的推移,不准确的情况会逐渐增加。您可以使用此脚本检查时间:

let lastTime = performance.now();
setInterval(() => {
    const currentTime = performance.now();
    console.log(currentTime - lastTime);
    lastTime = currentTime;
}, 1000);
Run Code Online (Sandbox Code Playgroud)


Mur*_*göz 6

您可以clearInterval(id)用来停止它。您必须存储setInterval例如的ID

const id = setInterval(() = > {
    this.setState({
        time: this.state.time + 1
    });
}, 1000)
clearInterval(id);
Run Code Online (Sandbox Code Playgroud)