今天写hooks是发现useEffect在使用lodash的防抖和节流是不管用了,于是就有了下面2个方法,记得别再踩坑奥~
import { useEffect } from 'react'
export {
useDebounce,
useThrottle
}
function useDebounce(fn, delay, dep = []) {
useEffect(() => {
let timer;
timer = setTimeout(fn, delay);
return () => clearTimeout(timer); // 这里用到useEffect清除的能力 类似于componentWillUnmount
}, [...dep]
)
}
function useThrottle(fn, delay, dep = []) {
const { current } = useRef({ fn, timer: null });
useEffect(function () {
current.fn = fn;
}, [fn]);
return useCallback(function f(...args) {
if (!current.timer) {
current.timer = setTimeout(() => {
delete current.timer;
}, delay);
current.fn.call(this, ...args);
}
}, dep);
}