用React hook写一个倒计时



import React, { useState, useEffect, useCallback, useRef } from 'react';

const CountDown: React.FC = () => {
  
  const intervalRef = useRef(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 (
    
  );
};

export default CountDown;

你可能感兴趣的:(学习,React,react)