简体   繁体   中英

Countdown timer multiple item

I'm using this package called react-countdown-now I have many items I'm just wondering why all the items counting down same time

https://codesandbox.io/s/4rpn84j5m0

As you can see below in my example the new item rest the old item

 import React, { Component } from 'react'; import { render } from 'react-dom'; import Countdown from 'react-countdown-now'; class App extends Component { constructor() { super(); this.state = { show: false }; } componentDidMount() { setTimeout(() => { this.setState({ show: true }) }, 2500) } render() { return ( <div> <Countdown date={Date.now() + 10000} /><br /> {this.state.show ? <Countdown date={Date.now() + 10000} /> : <span>waiting new item....</span>} <p> Why the new item rest the old item? </p> </div> ); } } render(<App />, document.getElementById('root')); 

Why the new item rest the old item?

The reason is because the expression Date.now() + 10000 gets recalculated on every re-render / state update. You need to store the dates somewhere.

As an example:

https://codesandbox.io/s/zq1mv4zmz4

import React, { Component } from "react";
import { render } from "react-dom";
import Countdown from "react-countdown-now";

class App extends Component {
  constructor() {
    super();

    this.state = {
      dates: [Date.now() + 10000]
    };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({ show: true });
    }, 2500);
  }

  render() {
    return (
      <div>
        {this.state.dates.map(date => (
          <div>
            <Countdown date={date} />
          </div>
        ))}
        <button onClick={() => this.addDate()}>New Item</button>
        <p>Why the new item rest the old item?</p>
      </div>
    );
  }

  addDate() {
    let dates = [...this.state.dates, Date.now() + 10000];
    this.setState({ dates });
  }
}

render(<App />, document.getElementById("root"));

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