【问题标题】:Stop timer on button click in React在 React 中单击按钮时停止计时器
【发布时间】:2021-03-26 11:12:38
【问题描述】:

我正在开发一个应用程序,我有一个显示当前日期、小时、分钟和秒数的计时器。它每秒递增一次。我想要做的是在单击按钮时停止计时器,但我不确定为什么 clearInterval() 函数不起作用。我的代码是:

class Timer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
           timer: "",
        };
    }

    componentDidMount() {
        //current time
        setInterval(() => {
            this.setState({
                currentTime : new Date().toLocaleString()
            })
        }, 1000)
    }


   stopTimer = () => {
        clearInterval(this.state.currentTime)
  }

   render() {
        return (
                <div>
                    <h4>Current time: {this.state.currentTime}</h4>
                    <Button onClick={this.stopTimer}>Stop timer</Button>
                </div>
              )
   }

}

【问题讨论】:

标签: javascript reactjs button timer onclick


【解决方案1】:

setInterval() 结果是intervalID,您应该将其用于clearInterval()

this.state = {
  ...
  intervalId: ""
};

...

const intervalId = setInterval(() => {
   ...
}, 1000);
this.setState({ intervalId });

...

clearInterval(this.state.intervalId);

【讨论】:

    【解决方案2】:

    您在错误的变量上使用了 clearInterval。你应该这样做。

    我正在开发一个应用程序,我有一个显示当前日期、小时、分钟和秒的计时器。它每秒递增一次。我想要做的是在单击按钮时停止计时器,但我不确定为什么 clearInterval() 函数不起作用。我的代码是:

    class Timer extends React.Component {
    
        constructor(props) {
            super(props);
            this.state = {
               timer: "",
               intervalId: ""
            };
        }
    
        componentDidMount() {
            //current time
           const intervalId =  setInterval(() => {
                this.setState({
                    currentTime : new Date().toLocaleString()
                })
            }, 1000); 
    
         this.setState({intervalId})
        }
    
    
       stopTimer = () => {
         if (this.state.intervalId) {
           clearInterval(this.state.intervelId)
         }
      }
    
       render() {
            return (
                    <div>
                        <h4>Current time: {this.state.currentTime}</h4>
                        <Button onClick={this.stopTimer}>Stop timer</Button>
                    </div>
                  )
       }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-23
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2022-12-31
      • 2012-10-17
      • 1970-01-01
      相关资源
      最近更新 更多