防抖(Debouncing)
在React中实现防抖功能,通常会使用useEffect
钩子结合外部的防抖函数。防抖的目的是在指定的延迟时间内如果连续触发事件,则只响应最后一次事件。这在处理如搜索输入框实时搜索等场景中尤其有用。
下面是一个使用lodash
库中的debounce
函数来实现防抖的例子:
jsximport React, { useState, useEffect } from 'react'; import { debounce } from 'lodash'; function SearchComponent() { const [inputValue, setInputValue] = useState(''); const debouncedSave = debounce((nextValue) => { // 实际的业务逻辑,比如调用API console.log('Saving data', nextValue); }, 1000); // 延迟1秒 useEffect(() => { debouncedSave(inputValue); // 清理函数,用于组件卸载时取消防抖动作 return () => debouncedSave.cancel(); }, [inputValue, debouncedSave]); return ( <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="Type to search..." /> ); }
在这个例子中,我们使用了useState
来存储输入框的值,并使用useEffect
来监听这个值的变化。当输入值变化时,useEffect
钩子会调用debouncedSave
函数,但由于这个函数是防抖过的,它只有在连续操作停止后才会执行。
节流(Throttling)
节流与防抖类似,但是它保证了在指定时间内最多只执行一次事件处理函数。这在处理像滚动事件这样的高频事件时非常有用,因为这些事件可能在短时间内触发很多次,而我们只需要稀疏地执行某些代码。
下面是一个使用lodash
库中的throttle
函数来实现节流的例子:
jsximport React, { useState, useEffect } from 'react'; import { throttle } from 'lodash'; function ScrollComponent() { const [position, setPosition] = useState(window.scrollY); const throttledHandleScroll = throttle(() => { setPosition(window.scrollY); console.log('Scroll position', window.scrollY); }, 1000); // 每1秒最多触发一次 useEffect(() => { window.addEventListener('scroll', throttledHandleScroll); return () => { window.removeEventListener('scroll', throttledHandleScroll); throttledHandleScroll.cancel(); } }, [throttledHandleScroll]); return ( <div> <p>当前滚动位置:{position}</p> </div> ); }
在这个例子中,我们创建了一个节流函数throttledHandleScroll
,这个函数在用户滚动页面时会执行,但是由于节流的作用,无论用户滚动得多频繁,它都只会每秒执行一次。我们还是用了useEffect
钩子来添加和清理事件监听器。
2024年6月29日 12:07 回复