import React, { Component } from 'react'
import axios from 'axios'
export default class Timer extends Component {
constructor(props) {
super(props)
this.state = {
bool: false,
days: '0',
hours: '00',
minutes: '00',
seconds: '00'
}
}
componentDidMount() {
this.start()
}
async start() {
this.timer && clearTimeout(this.timer) // 先清除一遍定时器,避免被调用多次
// 发起任意一个服务器请求, 然后从headers 里获取服务器时间
let leftTime = await axios.get('/').then(response => {
return new Date(this.props.date).getTime() - new Date(response.headers.date).getTime() // 服务器与倒计时的 时间差
}).catch(error => {
console.log(error)
return 0 // 这里发送的服务器请求失败 设为0
})
// 倒计时
this.timer = setInterval(() => {
leftTime = leftTime - 1000
let { bool, days = '0', hours = '00', minutes = '00', seconds = '00' } = this.countdown(leftTime)
if (bool) { // 结束倒计时
clearTimeout(this.timer)
}
this.setState({
bool,
days,
hours,
minutes,
seconds
})
}, 1000)
}
/**
* 倒计时
* @param leftTime 要倒计时的时间戳
*/
countdown(leftTime) {
let bool = false
if (leftTime <= 0) {
bool = true
return { bool }
}
var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10) //计算剩余的天数
var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10)
if (hours < 10) {
hours = '0' + hours
}
var minutes = parseInt(leftTime / 1000 / 60 % 60, 10)
if (minutes < 10) {
minutes = '0' + minutes
}
var seconds = parseInt(leftTime / 1000 % 60, 10)
if (seconds < 10) {
seconds = '0' + seconds
}
return { bool, days, hours, minutes, seconds }
}
componentWillUnmount() {
clearTimeout(this.timer)
}
render() {
let { bool, days, hours, minutes, seconds } = this.state
return (
<div>
{
bool ?
<div>活动已结束</div> :
<div>
{days} 天 {hours} : {minutes} : {seconds}
</div>
}
</div>
)
}
}
网友评论