How to start search only when user stops typing?

后端 未结 10 1804

I need to perform a Search when user stops typing.I know I am supposed to use setTimeout() . But with Reactjs I cant find how it works. Can

10条回答
  •  情书的邮戳
    2020-12-07 19:14

    Here's a working component template with some useful parameters to get your started.

    import React, { Component } from 'react'
    
    const initialState = { results: [], value: '' }
    
    export default class SearchBox extends Component {
      state = initialState
      timeout = null
      search_url = "https://example.com/search?q="
      min_query_length = 2
      timeout_duration = 300
    
      handleSearchChange = (e) => {
        let value = e.target.value
        clearTimeout(this.timeout);
        if (value.length < 1) {
            return this.setState(initialState) 
        } else {
            this.setState({ value })
            if (value.length>=this.min_query_length) {    
                this.timeout = setTimeout(this.search, this.timeout_duration);
            }
        }
      }
    
      search = () => {
        // assuming your results are returned as JSON
        fetch(`${this.search_url}${this.state.value}`)
        .then(res => res.json())
        .then(data => {
            this.setState({
                results: data,
            })
        })
      }
    
      render() {
        return (
              
        )
      }
    }
    
    

提交回复
热议问题