如何 slowdown/debounce 使用反应钩子处理事件?

How to slowdown/debounce events handling with react hooks?

处理滚动事件将经常触发。 slowdown/debounce有什么办法吗? 如果可能的话,我希望最后一个事件总是被触发而不是被跳过。

  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
}

使用钩子的事件处理程序可以像任何其他具有任何去抖实现的函数一样被去抖,例如Lodash:

  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

预计去抖动函数只会考虑最后一次调用,除非实现允许更改它,例如leadingtrailing 选项 Lodash debounce.

const debounceLoadData = useCallback(debounce((debounceValue)=>{  
    props.setSenderAddress(debounceValue)
}, 300), []);