gpt4 book ai didi

javascript - 在 react 中使用去抖动搜索输入

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:21:08 24 4
gpt4 key购买 nike

我有一个搜索输入,可以即时调用 API。我想实现去抖动以减少服务器调用量。

  _debouncedSearch() {
debounce(this.props.fetchRoutes(this.state.searchText), 1000);
}

_updateResults(searchText) {
this.setState({searchText});
this._debouncedSearch();
}

我期望每 1 秒执行一次 debouncedSearch。但它仍然被即时调用。并抛出错误:

Uncaught TypeError: Expected a function at debounce (lodash.js?3387:10334)

Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.

我觉得这个问题肯定被问过很多次,但似乎没有一个解决方案适合我。有人可以向我解释这里到底是什么问题吗?我认为 debounce 只是一个 setTimeOut。

谢谢

最佳答案

constructor(props) {
super(props);
this.state = {
searchText: '',
};
this._debouncedSearch = debounce(
() => this.props.fetchRoutes(this.state.searchText),
1000
);
}

_updateResults(searchText) {
this.setState({searchText});
this._debouncedSearch();
}

这是完整的工作代码,以备不时之需!

关于javascript - 在 react 中使用去抖动搜索输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47599589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com