useEffect(() => {
非同步函數 fetchPlaces() {
setIsFetching(true);
試 {
常量位置 = 等待
fetchAvailablePlaces();
navigator.geolocation.getCurrentPosition((position)=> {
const SortedPlaces = sortPlacesByDistance(
地點,
位置.座標.緯度,
位置.座標.經度
);
setAvailablePlaces(sortedPlaces);
setIsFetching(false);
})
} catch(錯誤) {
設定錯誤({
資訊:
錯誤訊息 || '無法取得地點,請稍後重試'});
}
setIsFetching(false);
}
fetchPlaces();
}, [])
如果(錯誤){
返回(
);
}
** 用於獲取和獲取資料的單獨文件 **
導出非同步函數 fetchAvailablePlaces(){
常量回應 = 等待
fetch('http://localhost:3000/places');
const resData =等待response.json();
if(!response.ok) { throw new Error('Failed to fetch places'); } return resData.places;
}
我想知道這種方法在建立 React 應用程式時如何處理錯誤。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3