Reasons and solutions for the failure of React event throttling effect

Reasons and solutions for the failure of React event throttling effect

Today, when I was working on a react project, I throttled an input onKeyDown event, but the throttling effect failed.

Problem code:

render() {
    return (
      <div className="search-bar">
        <input className="search-input" type="text" placeholder="Please enter the user name to search (English)" onKeyDown={this.throttle(this.handleKeyDown)}/>
      </div>
    )
  }
throttle = (fn) => {
    let valid = true
    const context = this

    return function() {
      if (!valid) return
      valid = false

      const args = arguments

      fn.apply(context, args)

      setTimeout(() => {
        valid = true
      }, 1000);
    }
  }

  handleKeyDown = (e) => {
    let { value } = e.target
    const keyCode = e.keyCode

    if (keyCode !== 13) return

    if (!value.trim()) return
    
    // Send search this.props.search(value)
  }

The problem here is:

this.props.search(value) in handleKeyDown() method
The component props are refreshed, triggering the react update flow lifecycle. Re-executed render();

In this way, the throttle() method will be re-executed;

throttle = (fn) => {
    console.log('%c throttle initialization', 'color: red');
    let valid = true
    const context = this

    return function() {
      if (!valid) return
      valid = false

      const args = arguments

      fn.apply(context, args)

      setTimeout(() => {
        valid = true
      }, 1000);
    }
  }

If you add printing to the code, you will see throttle initialization print multiple lines in the console;

Solution 1:

Put the throttling initialization position into the event function assignment

render() {
    return (
      <div className="search-bar">
        <input className="search-input" type="text" placeholder="Please enter the user name to search (English)" onKeyDown={this.handleKeyDown}/>
      </div>
    )
  }
handleKeyDown = this.throttle((e) => {
    let { value } = e.target
    const keyCode = e.keyCode

    if (keyCode !== 13) return

    if (!value.trim()) return
    
    // Send search this.props.search(value)
  })

Solution 2: Assign initialization in the constructor

render() {
    return (
      <div className="search-bar">
        <input className="search-input" type="text" placeholder="Please enter the user name to search (English)" onKeyDown={this.handleKeyDown}/>
      </div>
    )
  }
constructor(props) {
    super(props)
    this.handleKeyDown = this.throttle(this.handleSearch)
  }

  handleSearch = (e) => {
    let { value } = e.target
    const keyCode = e.keyCode

    if (keyCode !== 13) return

    if (!value.trim()) return
    
    // Send search this.props.search(value)
  }

Summary of mining pits:

To better understand the triggering mechanism of the react life cycle

The above is the detailed content of the reasons and solutions for the failure of React event throttling effect. For more information about the failure of React event throttling effect, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to introduce scss into react project
  • How to introduce Angular components in React
  • React introduces container components and display components to Vue
  • React internationalization react-intl usage
  • React Synthetic Events Explained
  • A brief comparison of Props in React
  • Detailed explanation of the solution for migrating antd+react projects to vite
  • React implementation example using Amap (react-amap)
  • A brief introduction to React

<<:  Examples of optimization techniques for slow query efficiency in MySQL IN statements

>>:  Explanation of Linux kernel optimization configuration for high-concurrency nginx server

Recommend

Vue implements the method example of tab routing switching component

Preface This article introduces the use of vue-ro...

Detailed explanation of VUE Token's invalidation process

Table of contents Target Thought Analysis Code la...

Zabbix's psk encryption combined with zabbix_get value

Since Zabbix version 3.0, it has supported encryp...

Detailed explanation of the basic usage of SSH's ssh-keygen command

SSH public key authentication is one of the SSH a...

What magical uses does CSS filter have

background Basic Concepts CSS filter property app...

Detailed explanation of MySQL combined index and leftmost matching principle

Preface I have seen many articles about the leftm...

Operate on two columns of data as new columns in sql

As shown below: select a1,a2,a1+a2 a,a1*a2 b,a1*1...

MySQL 5.6.33 installation and configuration tutorial under Linux

This tutorial shares the installation and configu...

Summary of several APIs or tips in HTML5 that cannot be missed

In previous blog posts, I have been focusing on so...

Tips for using top command in Linux

First, let me introduce the meaning of some field...

Example of Vue implementing fixed bottom component

Table of contents 【Effect】 【Implementation method...

Detailed explanation of deploying MySQL using Docker (data persistence)

This article briefly describes how to use Docker ...

Win32 MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...

Detailed installation and configuration tutorial of mysql5.7 on CentOS

Install Make sure your user has permission to ins...