gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:39:29 26 4
gpt4 key购买 nike

我是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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com