如何在Reack Hook 中封装公共防抖和节流 自定义hook
1、单独创建一个util.js 文件
import {useEffect ,useCallBack ,useRef} from "react"
/**
* 防抖
* @param {需要防抖的方法} fn
* @param {延迟时间,默认500ms} delay
* @param {useCallback 的第二个参数,默认为[]} dep
* @return 一个function
*/
export function useDoule(fn,delay=500,dep=[]){
const {curent}=useRef({fn,timer:null})
useEffect(()=>{current.fn=fn},[fn])
return useCallback(function(...args)){
if(current.timer)clearTimeout(current.timer)
current.timer=setTimeout(()=>{
current.fn.call(this,...args)
},delay)
},dep)
}
/**
* 节流
* @param {需要节流的方法} fn
* @param {延迟时间,默认500ms} delay
* @param {useCallback 的第二个参数,默认为[]} dep
* @return 一个function
*/
export function useThrottle(fn,delay=500,dep=[]){
const {curent}=useRef({fn,timer:0});
useEffect(()=>{curent.fn=fn},[fn]);
return useCallback(function(...args)){
let nowTime=nwe Date().getTime();
if(nowTime-current.timer>delay){
current.timer=nowTime;
current.fn.call(this,...args)
}
},dep)
}
2、如何应用:
import {useThrottle ,useDoule} from '@/common/util.js'
const test=()=>{
console.log('test')
}
const index(props)=>{
const Double=useDoule(test,1);
const Throttle=useThrottle(test,1);
return (
<div >
<button onClick={()=>double()}>double</button>
<button onClick={()=>Throttle()}>double</button>
</div>
)
}
export default Index
结尾:有问题欢迎提出,🙏🙏🙏🙏