You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

60 lines
1.2 KiB

/**
* 节流 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<T extends (...args: any[]) => 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<T>) => {
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);
*
* <ScrollView onScroll={handleScroll}>
* ...
* </ScrollView>
*/