React 中的 clearInterval

新手上路,请多包涵

我是 React 的新手,我试图创建一个带有开始和停止按钮的简单秒表。我正用头撞墙,试图通过停止按钮上的 onClick 事件来清除Interval。我会为 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;

原文由 Lucas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 929
1 个回答

您可以将间隔添加到组件的状态,并可以随时清除它。

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

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

原文由 Dinesh Patil 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进