倒计时组件
/*
* 订单倒计时
*/
import React, { useState, useRef, useEffect } from 'react';
interface TimeViewProps {
h: string; // 小时
m: string; // 分钟
s: string; // 秒
}
type TCountDownWapper = {
expire: string; //过期时间
setIsFresh?: any; // 是否刷新--用于控制倒计时结束后刷新页面
};
const CountDownWapper: React.FC<TCountDownWapper> = (props) => {
const countDownTimer = useRef<NodeJS.Timeout>(); // 倒计时标记
const [timeView, setTimeView] = useState<TimeViewProps | null>(null); // 倒计时显示
// 倒计时函数
const countDown = () => {
const nowTime = +new Date(); // 获取当前时间的时间戳(单位毫秒)
const expire = Date.parse(props.expire); // 过期时间转换为时间戳(单位毫秒)
const times = parseInt(`${(expire - nowTime) / 1000}`); // 把剩余时间毫秒数转化为秒
const h = parseInt(`${times / 60 / 60}`); // 小时
const m = parseInt(`${(times / 60) % 60}`); // 分钟
const s = parseInt(`${times % 60}`); // 秒
//设置时间格式
setTimeView({
h: h < 10 ? `0${h}` : `${h}`,
m: m < 10 ? `0${m}` : `${m}`,
s: s < 10 ? `0${s}` : `${s}`,
});
//时间判断
if (times <= 0) {
clearTimeout(countDownTimer.current);
setTimeView({ h: '00', m: '00', s: '00' });
} else {
countDownTimer.current = setTimeout(() => {
countDown();
}, 1000);
}
};
useEffect(() => {
// 如果倒计时归0则调取接口获取最新数据
if (timeView?.h == '00' && timeView?.m == '00' && timeView?.s == '00') props.setIsFresh(true);
}, [timeView]);
useEffect(() => {
if (props.expire) {
countDown();
} else {
setTimeView({ h: '00', m: '00', s: '00' });
}
return () => {
clearTimeout(countDownTimer.current);
};
}, []);
return (
<span>
{timeView?.h}:{timeView?.m}:{timeView?.s}
</span>
);
};
export default CountDownWapper;
父组件使用
expireTime是后端给的到期时间,isFresh,setIsFresh是前端在倒计时结束后刷新数据用的,下面只给出关键代码
const [isFresh, setIsFresh] = useState(false);
useEffect(() => {
if (isFresh) getData();
}, [isFresh]);
<CountDownWapper expire={expireTime} setIsFresh={setIsFresh} />