Perform debounce in React.js

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

    Julen solution is kind of hard to read, here's clearer and to-the-point react code for anyone who stumbled him based on title and not the tiny details of the question.

    tl;dr version: when you would update to observers send call a schedule method instead and that in turn will actually notify the observers (or perform ajax, etc)

    Complete jsfiddle with example component jsfiddle

    var InputField = React.createClass({
    
        getDefaultProps: function () {
            return {
                initialValue: '',
                onChange: null
            };
        },
    
        getInitialState: function () {
            return {
                value: this.props.initialValue
            };
        },
    
        render: function () {
            var state = this.state;
            return (
                
            );
        },
    
        onVolatileChange: function (event) {
            this.setState({ 
                value: event.target.value 
            });
    
            this.scheduleChange();
        },
    
        scheduleChange: _.debounce(function () {
            this.onChange();
        }, 250),
    
        onChange: function () {
            var props = this.props;
            if (props.onChange != null) {
                props.onChange.call(this, this.state.value)
            }
        },
    
    });
    

提交回复
热议问题