用React hook写一个倒计时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, { useState, useEffect, useCallback, useRef } from 'react';

const CountDown: React.FC = () => {
 
  const intervalRef = useRef<any>(null);
 
  const [count, changeCount] = useState(0);
 
  // 组件卸载时清除计时器
  useEffect(() => {
    return () => {
      clearInterval(intervalRef.current);
    };
  }, []);

  useEffect(() => {
    if (count === 59) {
      intervalRef.current = setInterval(() => {
        changeCount((preCount) => preCount - 1);
      }, 1000);
    } else if (count === 0) {
      clearInterval(intervalRef.current);
    }
  }, [count]);

  const onGetCaptcha = useCallback(() => {
    changeCount(59);
  }, []);

  return (
    <button type='button' disabled={!!count} onClick={onGetCaptcha}>
        {count ? `${count} s` : '获取验证码'}
    </button>
  );
};

export default CountDown;