我当前的实现基于类似问题的答案,该问题涉及如何在React中进行反跳,但是当我按照他们推荐的方式使用反跳时,对于搜索栏中的每个按键,反跳功能最终都会被多次调用
import { throttle, debounce } from 'throttle-debounce'
// 1.
public handleSearch = async e => {
e.preventDefault()
// value from onChange
const {
target: { value: input }
} = e
const { category, query, startSearch } = this.props
query(input)
// data sent to action creator
const data = {
input,
tags: input.replace(/\s/g, '').split(','),
category: category
}
this.startSearchDebounce(data)
}
// 3. is debounced for 5 seconds, but then makes calls for every keystroke
public handleCall = async data => this.props.startSearch(data)
// 2. should debounce action creator in handleCall for 5 seconds
public startSearchDebounce = debounce(5000, this.handleCall)
这是在其onChange中调用handleSearch函数的输入元素:
<input
type="text"
className="input spawnSearch"
placeholder="Search"
onChange={this.handleSearch}
value={input}
ref={this.inputRef}
/>
最后,我要反跳的动作创造者。在这里进行api调用。
export const startSearch = data => {
return async (dispatch, getState) => {
const conditions = {
...data,
id: getState().auth.id
}
// send api call here
const imageResultsByTag = await api.image.getAllByTags(conditions)
// then dispatch image results to store
return dispatch(search(imageResultsByTag))
}
}
当前正在发生的情况是,每次按键弹跳都会持续5秒钟,然后5秒钟后,服务器就会被api调用淹没。我认为它不触发一次的原因是因为在每次按键的handleSearch函数中调用startSearchDebounce时,由于某种原因,它都会创建一个新的debounce函数。我不知道为什么会这样,因为startSearchDebounce是在类实例上定义的。我在这里做什么错了?