error-handling - react Hook 和异步等待: Handling errors with Axios call

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

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

最佳答案

这是关于axios的事情。它返回 promise ,而不是它获得的值(value)。您需要使用它来处理错误。为此,您需要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();
    }, [])
基本上,您会说出Promise:如果调用成功,请在then中运行该函数,并将响应作为参数。如果失败,请在catch中运行该函数,但作为参数除外。然后,启动fetchData()。您需要处理在then块中收到的数据,因为Promise不会直接返回它。如果有问题,它将放在catch块中,然后在那里处理错误(也许在状态中设置一条错误消息并显示出来?)。
这是异步编程的重要组成部分,对我来说还是有点模糊,但这是一个更好地处理错误的好开始。

关于error-handling - react Hook 和异步等待: Handling errors with Axios call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63160130/

相关文章:

api - 在IBM Cloudant NoSQL DB上获取错误 “Payment Required”

ruby - 如何使用Ruby在密码失败时输出其他错误消息

swift - 什么时候在 Swift 错误处理中使用异常和可选值?

javascript - 无法将 JWT header 设置为 axios

javascript - axios 请求处理时防止用户刷新或退出

excel - 如何使我的 VBA 错误处理更有效率

javascript - 使用 React useContext 和 useReducer 时出现 Typescript 错误

javascript - react : How to skip useEffect on first render

reactjs - React,从 API 获取记录数据,但不呈现它?

node.js - 如何使用 axios 将图像(大文件)上传到服务器