Lodash用React Input去抖动

问题描述 投票:10回答:2

我正在尝试将lodash的debouncing添加到搜索函数中,从输入onChange事件调用。下面的代码生成一个类型错误'function is function',我理解,因为lodash期待一个函数。这样做的正确方法是什么,可以全部内联完成吗?到目前为止,我几乎尝试了所有的例子都无济于事。

search(e){
 let str = e.target.value;
 debounce(this.props.relay.setVariables({ query: str }), 500);
},
reactjs lodash relay debouncing
2个回答
18
投票

去抖函数可以在JSX中内联传递,也可以直接设置为类方法,如下所示:

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

小提琴:https://jsfiddle.net/woodenconsulting/69z2wepo/36453/

如果您正在使用es2015 +,您可以直接在constructorcomponentWillMount等生命周期方法中定义debounce方法。

例子:

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)
}

1
投票

这不是一个容易的问题

一方面只是解决你遇到的错误,你需要在函数中包装你setVariables

 search(e){
  let str = e.target.value;
  _.debounce(() => this.props.relay.setVariables({ query: str }), 500);
}

另一方面,我认为去抖逻辑必须封装在Relay中。

© www.soinside.com 2019 - 2024. All rights reserved.