【问题标题】:Using debounce with react don't fire function使用 debounce 和 react 不触发功能
【发布时间】:2018-02-16 00:29:02
【问题描述】:

我想在 react 中去抖一个函数,

import { debounce } from 'lodash';

<button onClick={this.handleClickDebounce}>Debounce click</button>

handleClickDebounce = () => {
    debounce(this.fire_something, 500);
  };

这里有什么问题?该功能甚至没有被触发。我在下面创建了一个演示

https://codesandbox.io/s/1r4k3r2z8l

【问题讨论】:

    标签: javascript reactjs ecmascript-6 lodash


    【解决方案1】:

    试试:

    constructor() {
        super();
    
        this.handleClickDebounce = debounce(this.handleClick, 500)
    }
    

    https://codesandbox.io/s/yk421z3om9

    【讨论】:

      【解决方案2】:

      constructor 中进行操作。在您的示例中,每次单击按钮时都会创建去抖动功能。但是函数应该只去抖动一次。

      工作示例 - https://codesandbox.io/s/rr6w91p3wo(打开控制台并尝试单击按钮)。

      class App extends Component {
        constructor() {
          super();
      
          this.handleClickDebounce = debounce(this.handleClick, 500);
        }
      
        handleClick = () => {
          this.fire_something();
        };
      
        fire_something = () => {
          console.log("fire");
        };
      
        render() {
          return (
            <div>
              <button onClick={this.handleClick}>Normal click</button>
              <br />
              <button onClick={this.handleClickDebounce}>Debounce click</button>
            </div>
          );
        }
      }
      
      ReactDOM.render(<App />, document.getElementById("root"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-01
        • 2020-07-02
        • 2021-12-14
        • 2019-07-26
        • 2021-08-21
        • 1970-01-01
        • 1970-01-01
        • 2018-07-15
        相关资源
        最近更新 更多