Perform debounce in React.js

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

    Uncontrolled Components

    You can use the event.persist() method.

    An example follows using underscore's _.debounce():

    var SearchBox = React.createClass({
    
      componentWillMount: function () {
         this.delayedCallback = _.debounce(function (event) {
           // `event.target` is accessible now
         }, 1000);
      },
    
      onChange: function (event) {
        event.persist();
        this.delayedCallback(event);
      },
    
      render: function () {
        return (
          
        );
      }
    
    });
    

    Edit: See this JSFiddle


    Controlled Components

    Update: the example above shows an uncontrolled component. I use controlled elements all the time so here's another example of the above, but without using the event.persist() "trickery".

    A JSFiddle is available as well. Example without underscore

    var SearchBox = React.createClass({
        getInitialState: function () {
            return {
                query: this.props.query
            };
        },
    
        componentWillMount: function () {
           this.handleSearchDebounced = _.debounce(function () {
               this.props.handleSearch.apply(this, [this.state.query]);
           }, 500);
        },
    
        onChange: function (event) {
          this.setState({query: event.target.value});
          this.handleSearchDebounced();
        },
    
        render: function () {
          return (
            
          );
        }
    });
    
    
    var Search = React.createClass({
        getInitialState: function () {
            return {
                result: this.props.query
            };
        },
    
        handleSearch: function (query) {
            this.setState({result: query});
        },
    
        render: function () {
          return (
            
          );
        }
    });
    
    React.render(, document.body);
    

    Edit: updated examples and JSFiddles to React 0.12

    Edit: updated examples to address the issue raised by Sebastien Lorber

    Edit: updated with jsfiddle that does not use underscore and uses plain javascript debounce.

提交回复
热议问题