The React search box implements anti-shake, onChange, and clearing

We often use the search box element, and the requirements generally look like this:

Gets live input and requests the results to be rendered to the list, as well as allowing the user to clear the input box

When implementing this requirement in React, consider the following:

  • The input image stabilization
  • Get the input value of onChange in an asynchronous operation
  • Set the value of input to the value of state to clear the input box

So, let’s first write out the input element

// search.tsx
import React, { useState, useEffect, useContext } from 'react'
const Search: React.FC = (props: any) => {
    const [listInput, setListInput] = useState({
        text: ' ',
        holder: 'Where are you going?',
        focus: false,
        suggestionIndex: 0,
        suggestion: [
          {text: ' ',list: []},
          {text: ' ',list: []}
        ],
        show: false,
        suggestionNoResult: false}) const addressOnchange: react. ChangeEventHandler<HTMLInputElement> = (e: React.ChangeEvent<HTMLInputElement>) => {react. ChangeEvent<HTMLInputElement>) =>setListInput({... listInput, text: e.target.value}) }return (
        <input type="text" value={listInput.text}   placeholder={listInput.holder} placeholder-style="color:#B7B9BE;" onChange={(e) => addressOnchange(e) } />
    )
}
Copy the code

At this point, the third point in the requirement, which is to allow the user to empty the input field has been implemented, the operation of the empty only need

setListInput({... listInput, text:' '})
Copy the code

But as an input box, the user input changes at any time, if according to this change in frequency to request the interface, not only increase a lot of unnecessary performance loss, but also may break the API, so anti-shake is a must.

// The state refresh initialization timeout must be placed outside the component definition of const Search due to the real-time setting of the input valueletChangeEventHandler<HTMLInputElement> = (e: React.ChangeEvent<HTMLInputElement>) => {if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => {
      console.log(e.target.value)
      // api request
    }, 800)
}
Copy the code

In this way, we have achieved the anti-shake, but careful children will find a problem, that is, E.target has become empty, can not get. In React, the asynchronous function calls function events using e.pineist ()

const addressOnchange: React.ChangeEventHandler<HTMLInputElement> = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.persist()
    setListInput({... ListInput, text: e.target.value}) //if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => {
      console.log(e.target.value)
      // api request
    }, 800)
}
Copy the code

In this way, we have the perfect foundation for search box stabilization, asynchronous requests, and clean input requirements. Please indicate the original source: juejin.cn/post/684490…