简体   繁体   English

React 中的 clearInterval

[英]clearInterval in React

I'm new at React and I was trying to create a simple stopwatch with a start and stop buttons.我是 React 的新手,我试图创建一个带有开始和停止按钮的简单秒表。 I'm banging my head against the wall to try to clearInterval with an onClick event on Stop button.我正用头撞墙,试图用停止按钮上的 onClick 事件清除Interval。 I would declare a variable for the setInterval and then would clear it using the clearInterval.我会为 setInterval 声明一个变量,然后使用 clearInterval 清除它。 Unfortunately it is not working.不幸的是,它不起作用。 Any tips?有小费吗? Thank you in advance.先感谢您。

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;

you can add interval to your component's state and can clear it whenever you want.您可以为组件的状态添加间隔,并可以随时清除它。

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

componentWillUnmount(){
  clearInterval(this.state.intervalId)
}

In your startHandler function you can do :在您的 startHandler 函数中,您可以执行以下操作:

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

and in your stopInterval() you would do clearInterval(this.myInterval);在你的stopInterval()你会做clearInterval(this.myInterval);

You can use clearInterval(id) to stop it.您可以使用clearInterval(id)来阻止它。 You have to store the id of the setInterval eg你必须存储setInterval的 id 例如

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

You can use setTimeout inside useEffect with no dependency so it calls once when the component is initiated, then call the clearInterval when the component is unmounted.您可以在useEffect使用setTimeout而不依赖它,因此它会在组件启动时调用一次,然后在组件卸载时调用clearInterval

useEffect(() => {
    let intervalId = setInterval(executingFunction,1000)
    return(() => {
        clearInterval(intervalId)
    })
},[])

Create an ID for the timer, then Change your start startHandler and stopHandler as below;为计时器创建一个 ID,然后更改您的 start startHandler 和 stopHandler 如下;

  let this.intervalID;

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

  }

  stopHandler() {
    clearInterval(intervalID)
  }

componentWillUnmount() will do the trick for stopping as well as resetting the stopwatch. componentWillUnmount() 将完成停止和重置秒表的技巧。 You can find more on this on react docs您可以在 react docs上找到更多相关信息

import React, { Component } from 'react';

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

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

  // Start the stopwatch
  startHandler() {
    this.stopWatchID = setInterval(()=>{
      this.setState({time:this.state.time + 1});
    },1000);
  }

  // Stop the stopwatch
  componentWillUnmount() {
    clearInterval(this.stopWatchID);
  }

  // Reset the stopwatch
  resetHandler(){
    this.setState({
        time: 0
    })
    this.componentWillUnmount();
  }

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

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

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

export default StopWatch;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM