hooks防抖
防抖
参考 https://blog.csdn.net/wangweiscsdn/article/details/107844516
import { useEffect, useRef, useCallback } from 'react'
interface currentType {
timer: any
fn: Function
}
export default function useDebounce(fn: Function, delay: number, dep = []) {
const { current } = useRef<currentType>({ fn, timer: null })
useEffect(
function () {
current.fn = fn
},
[fn],
)
return useCallback(function f(...args) {
if (current.timer) {
clearTimeout(current.timer)
}
current.timer = setTimeout(() => {
current.fn.call(this, ...args)
}, delay)
}, dep)
}
组件中使用
const onChangeInput = useDebounce((val: string) => {
console.log('开始请求', val)
Refetcher.refetchSearchUsers({ q: val })
setIsShowList(true)
}, 1500)
<Input
onChange={(e) => {
setSearchInput(e.target.value)
return onChangeInput(e.target.value)
}}
value={searchInput}
placeholder="输入用户名、id 搜索"
size="small"
h-40
/>