/** * 节流 Hook * 使用 lodash-es 的 throttle 函数 */ import { useEffect, useMemo, useRef } from 'react'; import { throttle } from 'lodash-es'; /** * 节流函数 Hook * @param callback 需要节流的函数 * @param delay 延迟时间(毫秒) * @param options 节流选项 * @returns 节流后的函数 */ export function useThrottle any>( callback: T, delay: number = 300, options?: { leading?: boolean; trailing?: boolean; } ): T { const callbackRef = useRef(callback); // 更新 callback ref useEffect(() => { callbackRef.current = callback; }, [callback]); // 创建节流函数 const throttledCallback = useMemo(() => { const func = (...args: Parameters) => { callbackRef.current(...args); }; return throttle(func, delay, options); }, [delay, options]); // 清理 useEffect(() => { return () => { throttledCallback.cancel(); }; }, [throttledCallback]); return throttledCallback as T; } /** * 使用示例: * * const handleScroll = useThrottle((event) => { * console.log('Scrolling:', event); * }, 200); * * * ... * */