如何在React JS中为两个玩家管理实现倒计时计时器的正确方法?

时间:2019-08-08 11:42:28

标签: reactjs react-native

我是React JS的新手。如何管理两个倒数计时器,先启动后倒数第二秒是在5秒间隔后启动和第一次停止。

它可以在单个时钟成功的情况下工作,但是添加两个时钟,然后第一次仅启动而不停止,而第二次不启动我不知道该怎么办?。

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
       isActive: true
    };
  }
 componentDidMount() {
    this.intervalId = setInterval(() => {
      this.randomCallObject();
    }, 5000);
  }
  randomCallObject() {
      this.setState({
      Active: !this.state.isActive
    });
  }
  render() {
     let clock= {
          time: 150,
          isActive:this.state.isActive
        }
    let clock2= {
          time: 100,
          isActive:!this.state.isActive
        }
    return (
     <div className="container">
        <Clcok ClockData={clock}/>
        <Clcok ClockData={clock2}/>
      </div>
    );
  }
}
import React, { Component } from "react";
const TOTAL_MINUTES = 60;
export default class ClockComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: props.ClockData.time,
      isActive: props.ClockData.isActive
    };
  }
  componentDidMount() {
    const { isActive } = this.state;
    if (isActive === true) {
      this.intervalId = setInterval(() => {
        const { time } = this.state;
        if (time > 0) {
          this.setState({
            time: time - 1
          });
        }
      }, 1000);
    }
  }
  componentWillUnmount() {
    clearInterval(this.intervalId);
  }
   render() {
    const { time } = this.state;
    let minutes ="" + Math.floor((time % (TOTAL_MINUTES * TOTAL_MINUTES))/ TOTAL_MINUTES);
    let seconds = "" + Math.floor(time % TOTAL_MINUTES);
    if (isNaN(minutes) || isNaN(seconds)) {
      return null;
    }
    if (minutes.length === 1) {
      minutes = `0${minutes}`;
    }
    if (seconds.length === 1) {
      seconds = `0${seconds}`;
    }
    return (
     <div className="row">
        <div className="col-md-1">
        <div> 
            {minutes}:{seconds}
       </div>
        </div>
       </div>
     );
  }
}

当时钟数据来自道具时,在isActive标志为true时将简单对象作为对象,然后在isActive false时将计时器打开,然后将计时器停止

1 个答案:

答案 0 :(得分:1)

要了解如何使用React处理setInterval,建议您阅读Dan Abramov的以下博客文章:

Making setInterval Declarative with React Hooks

在其中,他解释了如何使用setInterval使用React Hooks以及如何使用class组件。在帖子上,还提供了指向CodeSandbox示例的链接,您可以在其中查看其运行情况。

我所做的是创建另一个CodeSandbox,在这里您可以看到如何应用此示例来运行多个计时器:

https://codesandbox.io/embed/timers-l6me1

在示例中,我使用了React Hooks,因为它们不需要很多代码。

希望对您有帮助。

修改#1

这里是直接从所提到的文章中提取的Counter组件的示例,并经过修改以适合后一个示例。

class Counter extends React.Component {
  state = {
    count: 0,
    delay: 1000,
    isRunning: true
  };

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

  componentDidMount() {
    this.interval = setInterval(this.tick, this.state.delay);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.delay !== this.state.delay) {
      this.startInterval();
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  startInterval = () => {
    clearInterval(this.interval);
    this.interval = setInterval(this.tick, this.state.delay);
    console.log(this.interval);
  };

  tick = () => {
    this.setState({
      count: this.state.count + 1
    });
  };

  handleDelayChange = e => {
    this.setState({ delay: Number(e.target.value) });
  };

  toggleCounter = () => {
    console.log(this.state.isRunning);
    if (this.state.isRunning) {
      clearInterval(this.interval);
    } else {
      this.startInterval(this.state.delay);
    }
    this.setState({
      count: 0,
      isRunning: !this.state.isRunning
    });
  };

  render() {
    const {
      state: { isRunning, delay, count },
      toggleCounter,
      handleDelayChange
    } = this;

    return (
      <>
        <h1>{count}</h1>
        <input value={delay} onChange={handleDelayChange} />
        <button onClick={toggleCounter}>{isRunning ? "stop" : "start"}</button>
      </>
    );
  }
}