- 类组件中使用
import debounce from 'lodash.debounce'
class Pagination extends React.PureComponent<any, any> {
constructor(props: any) {
super(props)
this.handlePrev = debounce(this.handlePrev, 1000, {
leading: true,
trailing: false
})
}
handlePrev = () => {}
- 在函数式中使用
import debounce from 'lodash.debounce'
function Home(){
const haldeNext = useCallback(debounce(() => {}, 200), [])
return <></>
}
- 自定义防抖
import { useRef } from 'react'
/* fn (Function): 要防抖动的函数。
[delay=0] (number): 需要延迟的毫秒数。
[options=] (Object): 选项对象。
[options.leading=false] (boolean): 指定在延迟开始前调用。
[options.trailing=true] (boolean): 指定在延迟结束后调用
*/
function useDebounce(fn: any, delay: any, options: { leading?: boolean; trailing?: boolean } = { leading: false, trailing: true }) {
const { current } = useRef<any>({
timer: null,
dateTime: null
})
function f(...args: any[]) {
const endTime = new Date().getTime()
if (current.dateTime && options.leading && endTime - current.dateTime < delay) {
return false
} else if (options.leading) {
current.dateTime = new Date().getTime()
fn.bind(undefined, ...args)()
}
if (options.trailing) {
if (current.timer) {
clearTimeout(current.timer)
}
current.timer = setTimeout(fn.bind(undefined, ...args), delay)
}
}
return f
}
export default useDebounce
使用自定义防抖
const onActionButton = useDebounce(
async (item: any) => {
console.log('item', item)
},
1000,
{
leading: true,
trailing: false
}
)