lodash.debounce搜索反应js

时间:2017-07-27 21:21:35

标签: javascript reactjs lodash debouncing

我试图使用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)
}

有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:5)

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

import _, {debounce} from 'lodash';

此外,您还没有使用提取的功能:

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

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