自定义定时器hook

1. 通过useRef,useEffect定义一个定时器hook
import { useRef, useEffect } from 'react';

export default function useInterval(callback, delay) {
    const latestCallback = useRef(() => {});

    useEffect(() => {
        latestCallback.current = callback;
    });

    useEffect(() => {
        if (delay !== null) {
            const interval = setInterval(() => latestCallback.current(), delay || 0);
            return () => clearInterval(interval);
        }
        return undefined;
    }, [delay]);
}
2. 使用
import { useInterval } from 'utils'
const test = props => {
    const [count, setCount] = useState(5);
    useInterval(() => {
        setCount(count - 1);
    }, 1000);
    return (
        
            {count < 1 ? (
                

你可能感兴趣的:(自定义定时器hook)