Perform debounce in React.js

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

    Here is an example I came up with that wraps another class with a debouncer. This lends itself nicely to being made into a decorator/higher order function:

    export class DebouncedThingy extends React.Component {
        static ToDebounce = ['someProp', 'someProp2'];
        constructor(props) {
            super(props);
            this.state = {};
        }
        // On prop maybe changed
        componentWillReceiveProps = (nextProps) => {
            this.debouncedSetState();
        };
        // Before initial render
        componentWillMount = () => {
            // Set state then debounce it from here on out (consider using _.throttle)
            this.debouncedSetState();
            this.debouncedSetState = _.debounce(this.debouncedSetState, 300);
        };
        debouncedSetState = () => {
            this.setState(_.pick(this.props, DebouncedThingy.ToDebounce));
        };
        render() {
            const restOfProps = _.omit(this.props, DebouncedThingy.ToDebounce);
            return 
        }
    }
    

提交回复
热议问题