在React.js中添加去抖动

时间:2019-01-29 21:39:20

标签: javascript reactjs

此功能是通过onChange操作执行的。我只想评论下的内容在1秒后反跳。我该怎么做?

  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,
            });
          }
        });
  };
    });
}

1 个答案:

答案 0 :(得分:1)

只需将代码提取到新方法中,然后将其包装在_.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);
      }
    });
}