处理滚动事件会经常触发。有什么方法可以减缓/消除它?如果可能的话,我希望最后一个事件总是被触发而不是被跳过。
const handleScroll = event => {
//how to debounse scroll change?
//if you will just setValue here, it's will lag as hell on scroll
}
useEffect(() => {
window.addEventListener('scroll', handleScroll)
return () => {
window.removeEventListener('scroll', handleScroll)
}
}, [])
这是来自xnimorz的 useDebounce 钩子示例
import { useState, useEffect } from 'react'
export const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value)
useEffect(
() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handler)
}
},
[value, delay]
)
return debouncedValue
}