【发布时间】:2022-12-13 10:18:53
【问题描述】:
我的应用程序允许用户在搜索框中键入内容时进行搜索并获得建议。每次用户输入字符时,我都会使用“获取”从 API 获取建议。问题是如果用户快速搜索,他可以在获取建议之前得到结果。在这种情况下,我想取消获取请求。
我曾经在 React 中拥有相同的应用程序,我可以使用 AbortController 轻松取消请求,但这在 Next js 中不起作用。
我做了一些研究,我认为问题正在发生,因为 Next 在尝试生成页面时无法访问 AbortController。
当我尝试使用“window.innerWidth”时,我也遇到了这个问题,因为 Next 似乎也无法访问“window”。
我找到的解决方案是使用“useEffect”。当我将它与“窗口”一起使用时,它工作得很好。
const [size, setSize] = useState(0)
useEffect(() => {
setSize(window.innerWidth)
}, [])
但是当我使用 AbortController 时它不起作用。首先我是这样做的:
let suggestionsController;
useEffect(() => {
suggestionsController = new AbortController();
},[])
但是当我尝试使用“suggestionsController”时,它总是未定义。
所以我尝试使用“useRef”做同样的事情。
const suggestionsControllerRef = useRef(null)
useEffect(() => {
suggestionsControllerRef.current = new AbortController();
},[])
这就是我获取建议的方式:
async function fetchSuggestions (input){
try {
const response = await fetch(`url/${input}`, {signal: suggestionsControllerRef.current.signal})
const result = await response.json()
setSuggestionsList(result)
} catch (e) {
console.log(e)
}
}
这就是我中止请求的方式:
function handleSearch(word) {
suggestionsControllerRef.current.abort()
router.push(`/dictionary/${word}`)
setShowSuggestions(false)
}
一切都第一次完美运行。但是,如果用户尝试进行另一次搜索,“fetchSuggestions”功能将停止工作,并且我在控制台中收到此错误“DOMException:无法在‘Window’上执行‘fetch’:用户中止了请求”。
有谁知道在 Next js 中使用 AbortController 的正确方法是什么?
【问题讨论】:
标签: javascript next.js