• 35648

    文章

  • 23

    评论

  • 20

    友链

  • 最近新加了很多技术文章,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

React 涉及e.target时候,使用debounce节流函数

欢迎来到阿八个人博客网站。本 阿八个人博客 网站提供最新的站长新闻,各种互联网资讯。 喜欢本站的朋友可以收藏本站,或者加QQ:我们大家一起来交流技术! URL链接:https://www.abboke.com/jsh/2019/0823/107916.html 1190000020156100

React 涉及e.target时候,使用debounce节流函数

关键词: React, input, e.target, debounce

举例场景: 在一个input搜索框中输入文本,如果2s内可能会有很多次input的onChange事件,每次都触发一个API请求,明显不合理,所以此时需要debounce节流函数,2s之内的所有输入只会请求一次API,做到交互层面的优化。

为了缩小关注点,示例直接使用loadsh的debounce函数。也直接使用了类的示例属性方法(可用过babel支持,因为实在不喜欢写过多的bind)

==直接上正确代码:==

import React from 'react'
import {debounce} from 'lodash'

export default class InputDebounce extends React.Component {
  constructor() {
    super()
    this.doSearchAjax = debounce(this.doSearchAjax, 2000)
  }

  handleInputSearch = e => {
    this.doSearchAjax(e.target.value)
  }

  doSearchAjax = value => {
    console.log('执行AJAX搜索', value)
  }

  render() {
    return (
      <div>
        <h4>e.target 结合 debounce 使用</h4>
        <input type="text" onChange={this.handleInputSearch} />
      </div>
    )
  }
}

再来看常见的错误代码示例

一、直接使用debounce函数包裹事件函数

报错: Uncaught TypeError: Cannot read property 'value' of null

原因分析: 涉及到React中的合成事件,详见React合成事件,debounce包装后的回调函数,是个异步事件,即e.target为null了

解决方案: 使用e.persist()实现对事件的引用保留

import React from 'react'
import {debounce} from 'lodash'

export default class InputDebounce extends React.Component {
  handleInputSearch = e => {
    this.doSearchAjax(e.target.value)
  }

  doSearchAjax = value => {
    console.log('执行AJAX搜索')
  }

  render() {
    return (
      <div>
        <h4>e.target 结合 debounce 使用</h4>
        <input type="text" onChange={debounce(this.handleInputSearch, 2000)} />
      </div>
    )
  }
}

二、使用了e.persist(),但是 debounce 包含的函数并不会执行

import React from 'react'
import {debounce} from 'lodash'

export default class InputDebounce extends React.Component {
  handleInputSearch = e => {
    // 对原有事件进行保留
    e.persist()
    debounce(() => {
      // 函数并不会执行
      this.doSearchAjax(e.target.value)
    }, 2000)
  }

  doSearchAjax = value => {
    console.log('执行AJAX搜索')
  }

  render() {
    return (
      <div>
        <h4>e.target 结合 debounce 使用</h4>
        <input type="text" onChange={this.handleInputSearch} />
      </div>
    )
  }
}

这时候,需要将异步执行的函数抽离出来,即开头的正确代码。

正确代码里面并未使用e.persist(),因为没有必要,onChange函数并非是被debounce函数包装的。这里写出来只是为了记录踩坑,估计也有很多小伙伴掉过这个坑吧

相关文章

暂住......别动,不想说点什么吗?
  • 全部评论(0
    还没有评论,快来抢沙发吧!