Lodash debounce with React Input

后端 未结 7 1452
刺人心
刺人心 2021-02-05 04:54

I\'m trying to add debouncing with lodash to a search function, called from an input onChange event. The code below generates a type error \'function is expected\', which I unde

相关标签:
7条回答
  • 2021-02-05 05:55

    The debounce function can be passed inline in the JSX or set directly as a class method as seen here:

    search: _.debounce(function(e) {
      console.log('Debounced Event:', e);
    }, 1000)
    

    Fiddle: https://jsfiddle.net/woodenconsulting/69z2wepo/36453/

    If you're using es2015+ you can define your debounce method directly, in your constructor or in a lifecycle method like componentWillMount.

    Examples:

    class DebounceSamples extends React.Component {
      constructor(props) {
        super(props);
    
        // Method defined in constructor, alternatively could be in another lifecycle method
        // like componentWillMount
        this.search = _.debounce(e => {
          console.log('Debounced Event:', e);
        }, 1000);
      }
    
      // Define the method directly in your class
      search = _.debounce((e) => {
        console.log('Debounced Event:', e);
      }, 1000)
    }
    
    0 讨论(0)
提交回复
热议问题