react-native 防抖

  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
      }
    )
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、开源库介绍 今年1月份,新开源的React-natvigation库备受瞩目。在短短不到3个月的时间,gith...
    德山_阅读 2,236评论 0 19
  • 技术点: 不定期更新补充 页面引用svg symbol标签创建icon p:nth-child(2) 与 p:nt...
    wwmin_阅读 1,514评论 0 52
  • 在以下场景中,父组件和子组件通常会重新渲染:在同一组件或父组件中调用 setState 时。从父级收到的“prop...
    iien2121阅读 487评论 0 0
  • 前言 props与state都是用于组件存储数据的一js对象,前者是对外暴露数据接口,后者是对内组件的状态,它们决...
    itclanCoder阅读 2,191评论 0 0
  • Html5 语义化标签 headerfooternavarticlesection 文档类型定义 在h5中只需要写...
    路人丁0417阅读 1,123评论 0 2