简体   繁体   中英

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. I am not familiar with class programming with react and am having difficulty implementing this.

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

反负值

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() {
    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);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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