通过从React UI向后端发送少量/更少的请求来优化搜索结果



我正在向后端发送用户在输入字段中输入的请求,尽管我的UI有点滞后,但我已经实现了去抖动,我可以在去抖动的同时做/实现什么来改善搜索结果。

实际上,后端搜索是一个非常繁重的任务,有没有其他方法/技巧/技术可以用来进一步改进

[由于记录数量超过100000,我的后端处理请求大约需要1500到4000毫秒]

使用axios cancelToken功能非常有用,如果第一个请求的响应在第二个请求的回应之后到达,那么我们可能会呈现不一致的数据。

import axios from "axios"
import React from "react"
import "./App.css"
function App() {
let cancelToken
const handleSearchChange = async e => {
const searchTerm = e.target.value
//Check if there are any previous pending requests
if (typeof cancelToken != typeof undefined) {
cancelToken.cancel("Operation canceled due to new request.")
}
//Save the cancel token for the current request
cancelToken = axios.CancelToken.source()
try {
const results = await axios.get(
`http://localhost:4000/animals?q=${searchTerm}`,
{ cancelToken: cancelToken.token } //Pass the cancel token to the current request
)
console.log("Results for " + searchTerm + ": ", results.data)
} catch (error) {
console.log(error)
}
}
return (
<div style={{ marginTop: "3em", textAlign: "center" }}>
<input
style={{ width: "60%", height: "1.5rem" }}
type="text"
placeholder="Search"
onChange={handleSearchChange}
/>
</div>
)
}
export default App

最新更新