gpt4 book ai didi

reactjs - 如何使用 react 钩子(Hook)减慢/消除事件处理速度?

转载 作者:行者123 更新时间:2023-12-03 14:06:45 24 4
gpt4 key购买 nike

处理滚动事件将经常触发。有什么方法可以减慢/消除它的速度?如果可能的话,我希望最后一个事件始终被触发而不是被跳过。

  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 Hook 示例

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
}

最佳答案

使用钩子(Hook)的事件处理程序可以像具有任何去抖实现的任何其他函数一样进行去抖,例如洛达什:

  const updateValue = _.debounce(val => {
setState(val);
}, 100);

const handleScroll = event => {
// process event object if needed
updateValue(...);
}

请注意,由于 React 合成事件的工作方式,如果在事件处理程序中使用 event 对象,则需要同步处理它。

last event always be fired and not skipped

预计只有最后一次调用才会被考虑到去抖动函数,除非实现允许更改它,例如Lodash debounce 中的前导尾随 选项.

关于reactjs - 如何使用 react 钩子(Hook)减慢/消除事件处理速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54061464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com