了解在 useEffect 挂钩中捕获 try catch 错误的机制。为此,在 try 块中,我通过 throw new Error 创建错误,并且我认为,程序应该转到 catch 块,控制台日志将显示在屏幕上,但这不会发生。为什么会这样?
useEffect(() => {
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const response = await fetch(`/api/getCities?query=${query}`);
const body = await response.json();
if (response.status >= 500) {
throw new Error('Server Error');
}
//Создаю свою ошибку
throw new Error('My error');
setListCities(body);
} catch {
console.log('point 1');
setIsError(true);
console.log('point2');
}
setIsLoading(false);
};
fetchData();
}, [query]);
您的请求很可能会挂起
const response = await fetch(`/api/getCities?query=${query}`);
所以处理服务器。
try catch 没有问题: