Javascript 在React.js中添加debounce

Javascript 在React.js中添加debounce,javascript,reactjs,Javascript,Reactjs,此功能在onChange操作上执行。我只想在1s上消除评论中的内容。我怎样才能做到这一点 onChange = (event, { newValue }) => { this.setState({ value: newValue, }, () => { if (this.state.value.length !== 26) { // this debounce \/ this.Auth.getUsersData(newVal

此功能在
onChange
操作上执行。我只想在1s上消除评论中的内容。我怎样才能做到这一点

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue,
    }, () => {
      if (this.state.value.length !== 26) {
// this debounce \/
        this.Auth.getUsersData(newValue).then(res => {
          if (res) {
            this.setState({
              accountBills: res,
            });
          }
        });
  };
    });
}

只需将该代码提取到一个新方法中,并将其包装在
\u.debounce
中即可:

import {debounce} from 'lodash';

getUserData = debounce(newValue => this.Auth.getUsersData(newValue)
  .then(res => {
    if (res) { this.setState({ accountBills: res }) }
   })
, 1000);

onChange = (event, { newValue }) => {
    this.setState({
      value: newValue,
    }, () => {
      if (this.state.value.length !== 26) {
         this.getUserData(newValue);
      }
    });
}

我经常使用下划线库进行去噪。看看这个链接。您可以为getUser编写一个函数,然后const debounce=u.debounce(getUser,1000);debounce()比u更有效,但我必须这样做。getUserData(newValue);:)