index.js 2.14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
import React, { Component } from 'react';

function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

class Countdown extends Component {
  constructor(props) {
    super(props);

afc163's avatar
afc163 committed
11
    const { lastTime } = this.initTime(props);
12 13 14 15 16 17 18 19 20 21 22 23

    this.state = {
      lastTime,
    };
  }

  componentDidMount() {
    this.tick();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.target !== nextProps.target) {
afc163's avatar
afc163 committed
24
      const { lastTime } = this.initTime(nextProps);
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
      this.setState({
        lastTime,
      });
    }
  }

  componentWillUnmount() {
    clearTimeout(this.timer);
  }

  timer = 0;
  interval = 1000;
  initTime = (props) => {
    let lastTime = 0;
    let targetTime = 0;
    try {
      if (Object.prototype.toString.call(props.target) === '[object Date]') {
        targetTime = props.target.getTime();
      } else {
        targetTime = new Date(props.target).getTime();
      }
    } catch (e) {
      throw new Error('invalid target prop', e);
    }

    lastTime = targetTime - new Date().getTime();

    return {
      lastTime,
    };
  }
  // defaultFormat = time => (
  //  <span>{moment(time).format('hh:mm:ss')}</span>
  // );
  defaultFormat = (time) => {
    const hours = 60 * 60 * 1000;
    const minutes = 60 * 1000;

    const h = fixedZero(Math.floor(time / hours));
    const m = fixedZero(Math.floor((time - (h * hours)) / minutes));
    const s = fixedZero(Math.floor((time - (h * hours) - (m * minutes)) / 1000));
    return (
      <span>{h}:{m}:{s}</span>
    );
  }
  tick = () => {
    const { onEnd } = this.props;
    let { lastTime } = this.state;

    this.timer = setTimeout(() => {
      if (lastTime < this.interval) {
        clearTimeout(this.timer);
        this.setState({
          lastTime: 0,
        });

        if (onEnd) {
          onEnd();
        }
      } else {
        lastTime -= this.interval;
        this.setState({
          lastTime,
        });

        this.tick();
      }
    }, this.interval);
  }

  render() {
    const { format = this.defaultFormat } = this.props;
    const { lastTime } = this.state;

    const result = format(lastTime);

    return result;
  }
}

export default Countdown;