【问题标题】:timer countdown in reactjs doesn't worksreactjs中的计时器倒计时不起作用
【发布时间】:2021-05-31 21:47:10
【问题描述】:

我正在构建一个在一秒钟内计算点击次数的 Web 应用程序,但是 倒计时(从 5 到 0)不起作用。倒计时应该每秒(1000 毫秒)减少一次。我已经尝试使用 setInterval() 但它不起作用,现在我不知道我必须做什么

import React, {Component} from 'react';
import './App.scss';

class App extends Component {
  state = {
    count: 0,
    cps: 0,
    seconds: 5,
    target: '',
  }

  five = 5000;

  fiveSeconds = () => {
    this.increment = () => {
      this.setState({
        count: this.state.count + 1,
      })
    }
    this.countdown = setInterval(() => {
      this.setState({ seconds: this.state.seconds - 1})
      
      if (this.state.seconds <= 0){
        this.setState({ seconds: 0 });
      }
    }, 1000)

    this.timeout = setTimeout(() => {
      this.setState({ target: 'true', cps: this.state.count/this.five*1000 });

      if(this.state.count == 59){
        this.setState({ cps: 11.8 })
      }
    }, this.five)
  }

  render(){
    return (
      <div>
        <h3 id="counter-title">COUNTER: <a href="/" id="counter">{this.state.count}</a></h3>
        <h3 id="counter-title">CPS: {this.state.cps}</h3>
        <h3>TIMER: {this.state.seconds}</h3>
        <br/>
        <button disabled={this.state.target} id="btn" onClick={this.fiveSeconds}>CLICK HERE TO START</button>
      </div>
    );
  }
}

export default App;

【问题讨论】:

标签: javascript reactjs timer countdown


【解决方案1】:

我把你的代码放到了一个反应操场上,它似乎从 5 开始倒数。真正的问题是你可以多次点击按钮,每次点击都会触发fiveSeconds函数,这将大大加快倒计时的速度。

在第一次单击后,应通过在 FiveSeconds 函数中将“目标”状态变量设置为 true 来禁用该按钮,或者函数 FiveSeconds 应该只运行一次。一种方法是添加一个名为 ex 的新状态变量。 startFlag 初始化为 false 并在单击它后立即将 FiveSeconds 设置为 true。然后在按钮上放一个三元组,例如。 onClick={this.setFlag === false ? this.fiveSeconds : null}。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    相关资源
    最近更新 更多