」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 錯誤處理

錯誤處理

發佈於2024-09-02
瀏覽:864

Error Handling

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 應用程式時如何處理錯誤。

版本聲明 本文轉載於:https://dev.to/pravin_gaire_023f91e4e5a2/error-handling-3903?1如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3