Perform debounce in React.js

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

    a little late here but this should help. create this class(its written in typescript but its easy to convert it to javascript)

    export class debouncedMethod{
      constructor(method:T, debounceTime:number){
        this._method = method;
        this._debounceTime = debounceTime;
      }
      private _method:T;
      private _timeout:number;
      private _debounceTime:number;
      public invoke:T = ((...args:any[])=>{
        this._timeout && window.clearTimeout(this._timeout);
        this._timeout = window.setTimeout(()=>{
          (this._method as any)(...args);
        },this._debounceTime);
      }) as any;
    }
    

    and to use

    var foo = new debouncedMethod((name,age)=>{
     console.log(name,age);
    },500);
    foo.invoke("john",31);
    

提交回复
热议问题