React订单倒计时

倒计时组件

/*
 * 订单倒计时
 */
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} />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值