How to start search only when user stops typing?

后端 未结 10 1781

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:53

    Problem of Typeahead library https://twitter.github.io/typeahead.js/

    Since the case here is simple, I can use a quick and dirty solution:

    onChange: (event) ->
      if @_timeoutTask?
        clearTimeout @_timeoutTask
    
      @_timeoutTask = setTimeout (=>
        @sendToParent event.target.value
        clearTimeout @_timeoutTask
      ), 5000
    

    In this way, the task will be triggered 5s after input event. If new event happens, the old task will be cancelled and a new task is scheduled, then it's another 5s to wait.

    The difference in React is the where to store the computation state like _timeoutTask. The file scope, the component state, or the component instance.

    Since _timeoutTask is component level, it should be be store globally. And it does not affect rendering, so not in component state too. So I suggest attaching it to component instance directly.

提交回复
热议问题