react-app-shell
Version:
react打包脚本和example, 这里的版本请忽略
136 lines (118 loc) • 3.63 kB
JavaScript
import React, {Component} from 'react';
import {observer, inject} from 'mobx-react';
import PropTypes from 'prop-types';
import styles from './styles.less';
import queryString from 'query-string';
/**
* 团购活动结束倒计时组件
*/
(
({groupStore}) => {
return {
// 函数
loadData: groupStore.loadData,
};
}
)
export default class EndCountDown extends Component {
static propTypes = {
endTime: PropTypes.number.isRequired, // 活动开始时间
serverTime: PropTypes.number.isRequired, // 服务器时间
};
static defaultProps = {
endTime: 0,
serverTime: 0,
};
state = {
endTime: this.props.endTime,
serverTime: this.props.serverTime,
count: 0, // 倒计时毫秒数
isEnd: false,
msCount: 10 // 毫秒倒计时
};
componentDidMount() {
this.startCountDown(this.state.endTime, this.state.serverTime);
}
componentWillReceiveProps(nextProps) {
if (nextProps.endTime !== this.state.endTime || nextProps.serverTime !== this.state.serverTime) {
this.startCountDown(nextProps.endTime, nextProps.serverTime);
}
}
componentWillUnmount() {
/**
* 组件销毁 清除定时器
*/
clearInterval(this.timer);
}
timer = null;
startCountDown = (endTime, nowTime) => {
let count = 0;
// 如果活动结束时间为真, 并且大于当前时间, 则记录倒计时毫秒数
if (endTime && endTime > nowTime) {
count = endTime - nowTime;
}
this.setState({
endTime,
count,
serverTime: nowTime,
});
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);
};
/**
* 格式化时间
*/
getFormatTime = (count) => {
count = count / 1000;
let day = parseInt(count / 60 / 60 / 24, 10);
let hours = parseInt((count / 60 / 60) % 24, 10);
let minute = parseInt((count / 60) % 60, 10);
let second = parseInt(count % 60, 10);
return {
day,
hours,
minute,
second
};
};
render() {
let {count, msCount} = this.state;
const {day, hours, minute, second} = this.getFormatTime(count);
return (
<div className={styles['countdown']}>
<div className={styles['innercon']}>
<p>剩余时间</p>
<div className={styles['time']}>
<span>{day}</span>天
<span>{hours}</span>时
<span>{minute}</span>分
<span>{second}</span>秒
<span>{msCount}</span>
</div>
</div>
</div>
);
}
}