我怎样才能中止以前的 axios 调用或如何完美地进行自动完成
how can I abort previous axios call or how to do autocomplete perfectly
我正在尝试构建一个应用程序,用户可以在其中搜索各种项目。现在我的问题是如何有效地向服务器发送用户搜索请求?
例如,用户将输入一些内容(比如 15 个字符)。对于每 1 个字符,他向服务器发送一个请求(使用 axios)。现在他打字速度如此之快,在 3 秒内他向服务器发送了 15 个请求。由于 15 个并行请求,我的应用最近显示了实际结果(或有时失败)。请帮助我如何解决它。我正在使用带有 axios 的本机反应。
示例:
async searchLocation(text) {
if (text.length > 3) {
this.setState({searching: true, searchResultWindow: true});
var getSearchResult = await searchPlace(text); /// Here I am making axios call to our server
this.setState({searching: false, searchResults: getSearchResult.message});
}
}
您可以使用 setTimeout
来处理这种情况
let timer //the global variable to track the timer
async searchLocation(text) {
if (text.length > 3) {
//remove the API trigger within 3 seconds
clearTimeout(timer)
//assign new timer for the API call
timer = setTimeout(() => {
this.setState({searching: true, searchResultWindow: true});
var getSearchResult = await searchPlace(text); /// Here I am making axios call to our server
this.setState({searching: false, searchResults: getSearchResult.message});
}, 3000) //the API only triggers once users stop typing after 3 seconds
}
}
如果想更深入的了解,可以阅读这篇文章
https://www.freecodecamp.org/news/javascript-debounce-example/
我觉得你可以把这个问题分成两步
- 首先您必须找到用户想要输入的搜索词(不是搜索结果)
在这一步,你可以只使用字典
- 第二步是在按回车键或点击搜索按钮
后查找用户搜索结果
我正在尝试构建一个应用程序,用户可以在其中搜索各种项目。现在我的问题是如何有效地向服务器发送用户搜索请求?
例如,用户将输入一些内容(比如 15 个字符)。对于每 1 个字符,他向服务器发送一个请求(使用 axios)。现在他打字速度如此之快,在 3 秒内他向服务器发送了 15 个请求。由于 15 个并行请求,我的应用最近显示了实际结果(或有时失败)。请帮助我如何解决它。我正在使用带有 axios 的本机反应。
示例:
async searchLocation(text) {
if (text.length > 3) {
this.setState({searching: true, searchResultWindow: true});
var getSearchResult = await searchPlace(text); /// Here I am making axios call to our server
this.setState({searching: false, searchResults: getSearchResult.message});
}
}
您可以使用 setTimeout
来处理这种情况
let timer //the global variable to track the timer
async searchLocation(text) {
if (text.length > 3) {
//remove the API trigger within 3 seconds
clearTimeout(timer)
//assign new timer for the API call
timer = setTimeout(() => {
this.setState({searching: true, searchResultWindow: true});
var getSearchResult = await searchPlace(text); /// Here I am making axios call to our server
this.setState({searching: false, searchResults: getSearchResult.message});
}, 3000) //the API only triggers once users stop typing after 3 seconds
}
}
如果想更深入的了解,可以阅读这篇文章
https://www.freecodecamp.org/news/javascript-debounce-example/
我觉得你可以把这个问题分成两步
- 首先您必须找到用户想要输入的搜索词(不是搜索结果) 在这一步,你可以只使用字典
- 第二步是在按回车键或点击搜索按钮 后查找用户搜索结果