React中实现防抖功能的两种方式
生活随笔
收集整理的這篇文章主要介紹了
React中实现防抖功能的两种方式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問題
這有一個(gè)簡單的防抖函數(shù),短時(shí)間內(nèi)多次觸發(fā)同一事件,只執(zhí)行最后一次
function debounce (fn, wait) {let timer = nullreturn function (...args) {if (timer !== null) {clearTimeout(timer)}timer = setTimeout(() => {fn(args)timer = null}, wait)} }但問題是這個(gè)函數(shù)在react中使用不生效
export default () => {const handleClick = debounce(() => console.log("click fast!"), 1000));return (<button onClick={handleClick}>click fast!</button>); };原因就是函數(shù)式組件每次渲染,函數(shù)都會(huì)被重建,導(dǎo)致平時(shí)用的 debounce 函數(shù)中的timer會(huì)重新創(chuàng)建,進(jìn)而導(dǎo)致防抖失效。
方案一
使用useRef來緩存timer變量
export default function () {const click = useDebounce((e: Event) => {console.log(e);}, 1000)return (<button onClick={click}>按鈕</button>); }function useDebounce(fn: Function, delay: number) {const refTimer = useRef<number>();return function f(...args: any) {if (refTimer.current) {clearTimeout(refTimer.current);}refTimer.current = setTimeout(() => {fn(args);}, delay);} }方案二
使用useCallback來緩存函數(shù),只要第二個(gè)參數(shù)傳空數(shù)組,那么在組件重新選然時(shí),useCallback中的函數(shù)就不會(huì)重新創(chuàng)建
export default function DeBounce() {const click = useCallback(clickInner(), []);function clickInner() {let timer: number;return function (e: Event) {if (timer) {clearTimeout(timer);}timer = setTimeout(() => {console.log(e);}, 1000);}}return (<button onClick={click}>按鈕</button>); }總結(jié)
以上是生活随笔為你收集整理的React中实现防抖功能的两种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 看寒江独钓
- 下一篇: Lattice的构建过程