倒计时 react版

先看效果图:


活动开始之前.png
活动进行中.png
import { connect } from 'dva';
import styles from './index.less';

@connect(({ trailerGroupon }) => ({ ...trailerGroupon }))
export default class CountDown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      day: '-',
      hour: '-',
      minute: '-',
      second: '-'
    };
  }
  componentDidMount() {
    const { crowActRecord, isActivityStart, sysTime } = this.props;
    const { endTime, startTime } = crowActRecord;
    const time = isActivityStart ? endTime : startTime;
    // time = time.replace(/-/g, '/');
    this.countFun(time, sysTime);
  }

  componentWillReceiveProps(nextProps) {
    const { crowActRecord, isActivityStart, sysTime } = nextProps;
    const { endTime, startTime } = crowActRecord;
    const time = isActivityStart ? endTime : startTime;
    this.countFun(time, sysTime);
  }

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

  checkTime = time => time < 10 ? `0${time}` : time;

  countFun = (countdownTime, sysTime) => {
    clearInterval(this.timer);
    // const countdownTime = new Date(time).getTime();
    const currTime = sysTime || new Date().getTime();
    let sysSecond = Math.abs(countdownTime - currTime);
    this.timer = setInterval(() => {
      if (sysSecond > 1000) {
        sysSecond -= 1000;
        const day = Math.floor((sysSecond / 1000 / 3600) / 24);
        const hour = Math.floor((sysSecond / 1000 / 3600) % 24);
        const minute = Math.floor((sysSecond / 1000 / 60) % 60);
        const second = Math.floor((sysSecond / 1000) % 60);
        this.setState({
          day,
          hour: this.checkTime(hour),
          minute: this.checkTime(minute),
          second: this.checkTime(second)
        });
      } else {
        window.location.reload();
        clearInterval(this.timer);
      }
    }, 1000);
  }
  render() {
    const { isActivityStart, isActivityEnd } = this.props;
    const { day, hour, minute, second } = this.state;
    const ifActStart = isActivityStart ? `限时拼单结束还剩${day}天` : `距离活动开始还有${day}天`;
    return (
      
{!isActivityEnd ? ifActStart : '活动已结束'}   {!isActivityEnd && {hour}:{minute}:{second}}
); } }

crowActRecord 从服务器获取的包含开始时间和结束时间的对象。
isActivityStart 活动是否已经开始
isActivityEnd 活动是否已经结束
sysTime 服务器获取的系统时间

希望能帮助有需要的童鞋。

你可能感兴趣的:(倒计时 react版)