如何使用反应钩子减慢/消除事件处理速度? [英] How to slowdown/debounce events handling with react hooks?

查看:49
本文介绍了如何使用反应钩子减慢/消除事件处理速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理滚动事件会经常触发.有什么方法可以减缓/消除它?如果可能的话,我希望最后一个事件总是被触发而不是被跳过.

Handle scroll event will fire to often. What is the way to slowdown/debounce it? And if it's possible, i want last event always be fired and not skipped.

  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

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
}

推荐答案

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

Event handler that uses hooks can be debounced done the same way as any other function with any debounce implementation, e.g. Lodash:

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

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

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

Notice that due to how React synthetic events work, event object needs to be processed synchronously if it's used in event handler.

最后一个事件总是被触发而不被跳过

last event always be fired and not skipped

预计只有最后一次调用才会被去抖动函数考虑在内,除非实现允许更改它,例如Lodash debounceleadingtrailing 选项代码>.

It's expected that only the last call is taken into account with debounced function, unless the implementation allows to change this, e.g. leading and trailing options in Lodash debounce.

这篇关于如何使用反应钩子减慢/消除事件处理速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆