简体   繁体   English

React.js 类编程无法停止倒数计时器

[英]React.js class programming not able to stop count down timer

I am trying to stop the timer when the state count hits 0 or the state isStopped is true then it should stop it at that specific number.我试图在状态计数达到 0 或状态 isStopped 为真时停止计时器,然后它应该在该特定数字处停止它。 I am not familiar with class programming with react and am having difficulty implementing this.我不熟悉 React 的类编程,并且很难实现这一点。

I tried to look it up but I am not familiar with how to implement this using component did mount.我试图查找它,但我不熟悉如何使用组件确实安装来实现它。 I believe my logic should be correct on the component did mount portion however it never stops when it is 0 on the react app我相信我的逻辑在组件确实安装部分上应该是正确的但是当它在反应应用程序上为 0 时它永远不会停止

反负值

Here is my code这是我的代码

import React, { Component } from "react";
import "./index.css";

export default class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 10,
      isStopped: false,
    };
  }

  handleClick = () => {
    this.setState({ isStopped: !this.state.isStopped });
    console.log(this.state.isStopped);
  };

  render() {
    return (
      <div className="mt-100 layout-column align-items-center justify-content-center">
        <div className="timer-value" data-testid="timer-value">
          {this.state.count}
        </div>
        <button
          className="large"
          data-testid="stop-button"
          onClick={this.handleClick}
        >
          Stop Timer
        </button>
      </div>
    );
  }
  componentDidMount() {
    if (this.state.count > 0 && this.state.isStopped == false) {
      this.myInterval = setInterval(() => {
        this.setState({ count: this.state.count - 1 });
      }, 1000);
    }
  }
}

Any help would be appreciated thank you :)任何帮助将不胜感激谢谢:)

in componentDidMount() , clear the interval a/c to state:componentDidMount() ,清除间隔 a/c 以声明:

componentDidMount() {
    if (this.state.count > 0 && this.state.isStopped == false) {
      this.myInterval = setInterval(() => {

       if (this.state.isStopped) {
           clearInterval(this.myInterval);
           return;
       }

        this.setState({ count: this.state.count - 1 });
      }, 1000);
    }
    
    
  }

Code Sandbox Link 代码沙盒链接

You can use the below login您可以使用以下登录

componentDidMount() {
    if (this.state.count > 0) {
      this.myInterval = setInterval(() => {

       if (this.state.isStopped) {
           clearInterval(this.myInterval);
           return;
       }
        this.setState({ count: this.state.count - 1 });
      }, 1000);
    }
  }

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

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