Perform debounce in React.js

前端 未结 30 1564
礼貌的吻别
礼貌的吻别 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:30

    for throttle or debounce the best way is to create a function creator so you can use it any where, for example:

      updateUserProfileField(fieldName) {
        const handler = throttle(value => {
          console.log(fieldName, value);
        }, 400);
        return evt => handler(evt.target.value.trim());
      }
    

    and in your render method you can do:

    
    

    the updateUserProfileField method will create a separated function each time you call it.

    Note don't try to return the handler directly for example this will not work:

     updateUserProfileField(fieldName) {
        return evt => throttle(value => {
          console.log(fieldName, value);
        }, 400)(evt.target.value.trim());
      }
    

    the reason why this will not work because this will generate a new throttle function each time the event called instead of using the same throttle function, so basically the throttle will be useless ;)

    Also if you use debounce or throttle you don't need setTimeout or clearTimeout, this is actually why we use them :P

提交回复
热议问题