Lodash 中的防抖函数 debounce 在react中的应用

770 阅读1分钟

Lodash 中的防抖函数 debounce 在react中的应用

引用

import debounce from 'lodash/debounce';

类组件

<input onChange={this.onChange} />
// class组件中通过绑定到this上来保证不同生命周期中handleChange的引用不变
onChange = e => {
   e.persist();
   if (!this.handleChangeDebounce) {
     this.handleChangeDebounce = debounce(this.handleChange, 500);
   }
   this.handleChangeDebounce(e);
 };
handleChange = e => {
 //具体的业务逻辑
}

函数组件

<Input  onChange={e=>debounceQueryAccountInfo()} />

const queryAccountInfo = useCallback(
   (e) => {
       //具体的业务逻辑
  }, [],
);
const debounceQueryAccountInfo = useCallback(
  debounce(value => queryAccountInfo(value), 500), [queryAccountInfo]);