【基础向】react hooks定时器封装

73 阅读1分钟

来源https://www.jianshu.com/p/5cb3a84dd40b

// 定时器

export function useSetInterval(callback, delay) {
    if (!(callback instanceof Function)) {
        throw new Error("callback 参数必须是函数!");
    }
    if (!(delay === null || typeof delay === "number")) {
        throw new Error("delay 必须是 null 或者数字!");
    }
    const savedCallback = useRef();

    useEffect(() => {
        savedCallback.current = callback;
    }, [callback]);

    useEffect(() => {
        if (delay === null) {
            return;
        }
        let id = null;
        const tick = () => {
            const returnValue = savedCallback.current();
            if (returnValue) {
                console.log("come in");
                if (returnValue instanceof Function) {
                    returnValue();
                } else {
                    throw new Error("返回值必须是函数!");
                }
                clearTimeout(id);
                return;
            }
            id = setTimeout(tick, delay);
        };
        id = setTimeout(tick, delay);
        return () => clearInterval(id);
    }, [delay]);

//引用
useSetInterval(() => {
    if (count <= 0) {
      return () => {
        // 定时器消除后的代码逻辑
        setDelay(null);
        setCount(6);
      };
    }
    setCount(count - 1);
  }, delay);
}