react-Hook倒计时hook

我们平常注册账号的时候会有发送验证码的需求,为了减少过多的请求,我们一般限制60s发一次,这个需求也很平常,但在react中之前我并没有写过,就简单的研究了一下,把该需求封装成了一个hook

代码
import { useCallback, useEffect, useRef, useState } from "react";
//initCount是倒计时时长,默认是10s,callBack是开始执行的回调函数,endBack是结束时执行的函数
export function useCountDown(
  initCount = 10,
  callBack = () => {},
  endBack = () => {}
) {
//初始化定时器id
  const timeId = useRef<{ id: number }>({ id: 0 });
  //初始化倒计时
  const [count, setCount] = useState(initCount);
  //初始化是否禁用
  const [isdisable, setIsdisable] = useState(false);
  //开始,执行该函数之后会开启倒计时
  const start = () => {
    setCount(initCount);
    setIsdisable(true);
    timeId.current.id = window.setInterval(() => {
      setCount((count) => count - 1);
    }, 1000);
  };
  //   首先清除定时器
  useEffect(() => window.clearInterval(timeId.current.id), []);
  //   判断是否需要清除
  useEffect(() => {
    if (count !== initCount || isdisable) {
      callBack();
    }
    if (count === 0) {
      clearInterval(timeId.current.id);
      setCount(initCount);
      endBack();
      setIsdisable(false);
    }
  }, [callBack, count, initCount, endBack, isdisable]);
  //对外暴露三个属性,开始执行函数,当前倒计时时间,是否禁用
  return { start, count, isdisable };
}
使用
import React, { useState } from 'react'
import { useCountDown } from '../../hooks/utils';
import { Button } from 'antd';

export default function text() {
    const [codeMessage, setCodeMessage] = useState("获取验证码");
    const { start, count, isdisable } = useCountDown(
        60,
        () => {
            setCodeMessage(`${count}s后重新获取`);
        },
        () => {
            setCodeMessage("获取验证码");
        }
    );
    function getCode() {
        start();
    }
    return (
        <div>
            <Button
                onClick={getCode}
                disabled={isdisable}
                style={{ marginLeft: "10px" }}
            >
                {codeMessage}
            </Button>
        </div>
    )
}

以上就是我封装的倒计时hook。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值