UNPKG

react-app-shell

Version:

react打包脚本和example, 这里的版本请忽略

168 lines (125 loc) 3.81 kB
import React, {Component} from 'react'; import {observer, inject} from 'mobx-react'; import PropTypes from 'prop-types'; import queryString from 'query-string'; import styles from './not-begin-count-down.less'; /** * 团购活动未开始的倒计时组件 */ @inject( ({SpecialGroupStore}) => { return { // 函数 loadData: SpecialGroupStore.loadData, }; } ) @observer class NotBeginCountDown extends Component { static propTypes = { startTime: PropTypes.number.isRequired, // 活动开始时间 serverTime: PropTypes.number.isRequired, // 服务器时间 }; static defaultProps = { startTime: 0, serverTime: 0, }; constructor(props) { super(props); const {startTime, serverTime} = this.props; this.state = { startTime: startTime, serverTime: serverTime, count: 0, // 倒计时毫秒数 msCount: 10 // 毫秒倒计时 }; } componentDidMount() { this.startCountDown(this.state.startTime, this.state.serverTime); } componentWillReceiveProps(nextProps) { if (nextProps.startTime !== this.state.startTime) { this.startCountDown(nextProps.startTime, nextProps.serverTime); } } componentWillUnmount() { /** * 组件销毁 清除定时器 */ clearInterval(this.timer); } timer = null; startCountDown = (startTime, nowTime) => { let count = 0; // 如果活动开始时间为真, 并且大于当前时间, 则记录倒计时毫秒数 if (startTime && startTime > nowTime) { count = startTime - nowTime; } this.setState({ startTime, count, }); clearInterval(this.timer); if (count === 0) { return; } this.timer = setInterval(() => { let {count, msCount} = this.state; msCount = msCount - 1; if (count && msCount === 0) { count = count - 1000; msCount = 10; } if (count && count < 0 || count === 0) { count = 0; clearInterval(this.timer); // 重新加载数据 const {groupId, teamId} = queryString.parse(window.location.search); this.props.loadData(groupId, teamId); } this.setState({ count, msCount }); }, 100); }; /** * 获取倒计时的格式 * @param count */ getFormatTime = (count) => { count = count / 1000; let day = this.fillZero(parseInt(count / 60 / 60 / 24, 10)); let hours = this.fillZero(parseInt((count / 60 / 60) % 24, 10)); let minute = this.fillZero(parseInt((count / 60) % 60, 10)); let second = this.fillZero(parseInt(count % 60, 10)); return { day, hours, minute, second }; }; fillZero = (num) => { if (num < 10) { num = '0' + num; } return num; }; render() { let {count, msCount} = this.state; const {day, hours, minute, second} = this.getFormatTime(count); return ( <div> <div className={styles['time']}> <span>{day}</span>&nbsp;:&nbsp; <span>{hours}</span>&nbsp;:&nbsp; <span>{minute}</span>&nbsp;:&nbsp; <span>{second}</span>&nbsp;&nbsp; <span>{msCount}</span> </div> </div> ); } } export default NotBeginCountDown;