Perform debounce in React.js

前端 未结 30 1471
礼貌的吻别
礼貌的吻别 2020-11-22 04:11

How do you perform debounce in React.js?

I want to debounce the handleOnChange.

I tried with debounce(this.handleOnChange, 200) but it doesn\'t

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 04:53

    If you are using redux you can do this in a very elegant way with middleware. You can define a Debounce middleware as:

    var timeout;
    export default store => next => action => {
      const { meta = {} } = action;
      if(meta.debounce){
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          next(action)
        }, meta.debounce)
      }else{
        next(action)
      }
    }
    

    You can then add debouncing to action creators, such as:

    export default debouncedAction = (payload) => ({
      type : 'DEBOUNCED_ACTION',
      payload : payload,
      meta : {debounce : 300}
    }
    

    There's actually already middleware you can get off npm to do this for you.

提交回复
热议问题