How to start search only when user stops typing?

后端 未结 10 1790

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 18:57

    I think we can do it in a more simpler and cleaner manner, without abrupting the state parameter which calls the complete component life cycle like this:

    constructor(props) {
        super(props);
    
        //Timer
        this.typingTimeout = null;
    
        //Event
        this.onFieldChange = this.onFieldChange.bind(this);
    
        //State
        this.state = { searchValue: '' }; 
    }   
    
    
     /**
     * Called on the change of the textbox.
     * @param  {[Object]} event [Event object.]
     */
    onFieldChange(event) {
        // Clears the previously set timer.
        clearTimeout(this.typingTimeout);
    
        // Reset the timer, to make the http call after 475MS (this.callSearch is a method which will call the search API. Don't forget to bind it in constructor.)
        this.typingTimeout = setTimeout(this.callSearch, 475);
    
        // Setting value of the search box to a state.
        this.setState({ [event.target.name]: event.target.value });
    }
    
    
    

提交回复
热议问题