加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – Lodash用React Input去抖动

发布时间:2020-12-15 20:45:49 所属栏目:百科 来源:网络整理
导读:我正在尝试将lodash的debouncing添加到搜索函数中,从输入onChange事件调用.下面的代码生成一个类型错误’function is expected’,我理解,因为lodash期待一个函数.这样做的正确方法是什么,可以全部内联完成吗?到目前为止,我几乎尝试了所有的例子都无济于事.
我正在尝试将lodash的debouncing添加到搜索函数中,从输入onChange事件调用.下面的代码生成一个类型错误’function is expected’,我理解,因为lodash期待一个函数.这样做的正确方法是什么,可以全部内联完成吗?到目前为止,我几乎尝试了所有的例子都无济于事.
search(e){
 let str = e.target.value;
 debounce(this.props.relay.setVariables({ query: str }),500);
},
debounce函数可以在JSX中内联传递,也可以直接设置为类方法,如下所示:
search: _.debounce(function(e) {
  console.log('Debounced Event:',e);
},1000)

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

如果您使用的是es2015,则可以直接在构造函数或componentWillMount等生命周期方法中定义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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读