【问题标题】:React Hooks & Async Await: Handling errors with Axios callReact Hooks & Async Await:使用 Axios 调用处理错误
【发布时间】:2020-11-19 10:17:51
【问题描述】:

我是 hooksasync/await 的新手。我正在尝试处理 Axios 调用中的错误,但我不确定如何使用 then/catchtry/catch 来处理我的 API 调用中的错误。

在基于类的 React 中,我会处理这样的错误:

componentDidMount() {
       axios.get('url')
        .then((res) => {
            // handle response here
        })
        .catch((err) => {
            //handle error here
        })
   };

使用useEffectasync/await时如何处理Axios错误处理?我已经看到使用 try/catch 的示例,但我无法让它在我的代码中工作。

如何向以下 API 调用添加错误处理:

useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            const data =  await axios.get(`https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=Miami&state_code=FL&limit=100&offset=0`, headers);

            const properties = data.data.properties;
            console.log(properties);

            /// Iterates through data and grabs all the data for house listings
            const listings =  properties.map((listing, index) => {
                const arr = [];
                arr.push(
                    listing.listing_id,
                    listing.address.line, 
                    listing.address.city, 
                    listing.address.county, 
                    listing.address.neighborhood_name, 
                    listing.address.state,
                    listing.year_built,
                    listing.address.lat,
                    listing.address.lon);

                arr.push(listing.photos.map((photo) => {
                    return photo.href;
                }));

                return arr;
            });

            // House listing data is put into houseData
            //getHouseData(listings);
            setListings(listings);
            setLoading(false);
        }
        fetchData();
    }, [])

【问题讨论】:

    标签: error-handling axios react-hooks try-catch use-effect


    【解决方案1】:

    这是关于 axios 的。它返回承诺,而不是它获得的价值。您需要使用它来处理错误。为此,您需要 then()catch() 方法。示例:

    useEffect(() => {
            const fetchData = async () => {
                setLoading(true);
                await axios.get(`https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=Miami&state_code=FL&limit=100&offset=0`, headers).then((response)=>{
                 /* DO STUFF WHEN THE CALLS SUCCEEDS */
                 setLoading(false);
                }).catch((e)=>{
                 /* HANDLE THE ERROR (e) */
                });
            }
            fetchData();
        }, [])
    

    基本上,您告诉承诺:如果调用成功,则运行 then 中的函数,并将响应作为参数。如果失败,则运行catch 中的函数,并将异常作为参数。然后,您启动 fetchData()。您需要处理在 then 块中收到的数据,因为承诺不会直接返回它。如果有问题,它会进入catch 块,你在那里处理你的错误(也许在状态中设置一个错误消息并显示它?)。

    这是异步编程的重要组成部分,对我来说仍然有点模糊,但这是更充分地处理错误的良好开端。

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 2021-10-24
      • 2018-09-03
      • 1970-01-01
      • 2019-01-05
      • 2020-09-10
      • 2021-10-30
      • 2021-12-31
      • 2021-04-01
      相关资源
      最近更新 更多