react-native 防抖

2023-10-27  本文已影响0人  Biao_349d
  1. 类组件中使用

import debounce from 'lodash.debounce'

class Pagination extends React.PureComponent<any, any> {
  constructor(props: any) {
    super(props)
    this.handlePrev = debounce(this.handlePrev, 1000, {
      leading: true,
      trailing: false
    })
  }

handlePrev  = () => {}

  1. 在函数式中使用
    import debounce from 'lodash.debounce'
function Home(){
const   haldeNext = useCallback(debounce(() => {}, 200), [])
  return <></>
}
  1. 自定义防抖
import { useRef } from 'react'

/* fn (Function): 要防抖动的函数。
[delay=0] (number): 需要延迟的毫秒数。
[options=] (Object): 选项对象。
[options.leading=false] (boolean): 指定在延迟开始前调用。
[options.trailing=true] (boolean): 指定在延迟结束后调用
*/
function useDebounce(fn: any, delay: any, options: { leading?: boolean; trailing?: boolean } = { leading: false, trailing: true }) {
  const { current } = useRef<any>({
    timer: null,
    dateTime: null
  })
  function f(...args: any[]) {
    const endTime = new Date().getTime()
    if (current.dateTime && options.leading && endTime - current.dateTime < delay) {
      return false
    } else if (options.leading) {
      current.dateTime = new Date().getTime()
      fn.bind(undefined, ...args)()
    }
    if (options.trailing) {
      if (current.timer) {
        clearTimeout(current.timer)
      }
      current.timer = setTimeout(fn.bind(undefined, ...args), delay)
    }
  }

  return f
}

export default useDebounce

使用自定义防抖


    const onActionButton = useDebounce(
      async (item: any) => {
        console.log('item', item)
      },
      1000,
      {
        leading: true,
        trailing: false
      }
    )
上一篇下一篇

猜你喜欢

热点阅读