【问题标题】:lodash.debounce search in react jsreact js中的lodash.debounce搜索
【发布时间】:2018-01-03 19:10:25
【问题描述】:

我正在尝试使用 lodash, debounce 来消除响应中的搜索抖动。

但是当它运行时,我会收到一个类型错误

TypeError: Cannot read property 'debounce' of undefined

我尝试在代码中移动它,但不明白为什么它不起作用

我从导入它开始

import { _, debounce } from 'lodash'

我有如下输入

<input
    type="text"
    value={this.state.query}
    onChange={(e) => {this.updateQuery(e.target.value)}}
    placeholder="Search by title or author"
/>

连接到这个函数

updateQuery = (query) => {
    _.debounce(() => query(this.setState({ query }), 500))
    this.onBookSearch(query)
}

有人知道这是为什么吗?

【问题讨论】:

  • 听起来你的 node_modules 中实际上并没有 lodash。你忘了npm install --save lodash吗?
  • 嗨,是的,我有。感谢您的检查。下面的解决方案有效
  • 你能解释一下 query( this.setState()..), 500) 在 debounce 函数中的含义吗?

标签: javascript reactjs lodash debouncing


【解决方案1】:

我认为您的导入是问题所在。您可能希望将 _ 作为默认值导入:

import _, {debounce} from 'lodash';

另外你没有使用提取的函数:

updateQuery = (query) => {
  debounce(() => query(this.setState({ query }), 500))
  this.onBookSearch(query)
}

由于您在导入中提取{debounce},因此您可以直接使用它。

【讨论】:

  • 你能解释一下 query( this.setState()..), 500) 在 debounce 函数中的含义吗?
猜你喜欢
  • 1970-01-01
  • 2018-01-15
  • 2022-08-03
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 2015-06-28
相关资源
最近更新 更多