首页 > 解决方案 > React Hooks & Async Await:使用 Axios 调用处理错误

问题描述

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

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

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

useEffect使用and时如何处理 Axios 错误处理async/await?我已经看到使用示例,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-handlingaxiosreact-hookstry-catchuse-effect

解决方案


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

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();
    }, [])

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

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


推荐阅读