error-handling - React Hooks & Async Await:使用 Axios 调用处理错误
问题描述
我是hooks
和的新手async/await
。我正在尝试处理 Axios 调用中的错误,但我不确定如何使用then/catch
或try/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();
}, [])
解决方案
这是关于 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
块,你在那里处理你的错误(也许在状态中设置一个错误消息并显示它?)。
这是异步编程的重要组成部分,对我来说仍然有点模糊,但这是更充分地处理错误的良好开端。
推荐阅读
- c++ - 我是 C++ 新手,我想知道,为什么在 C++ 中使用纯虚函数?为什么要使用纯虚函数?
- amazon-web-services - AWS 子网间路由问题
- sql - 为什么一个带有额外连接的查询比对规范化数据的相同查询(少一个连接)更快?
- javascript - 未捕获的 TypeError:jQuery(...).slick 不是 Wordpress 自定义模板中的函数
- docker - Wso2 EI作为docker容器运行时日志的位置是什么
- flutter - 如何让 ListView.builder() 小部件的高度成为整个堆栈的高度?
- html - 如何摆脱网格 css 布局中的空格并将元素一个接一个地放置在一起
- android - 仅在按照意图进行时才更改片段(在这种情况下,他们实际上共享应用程序)
- sql-server - Azure SQL 数据库分区
- python - 使用 fastai 图像增强降低了我的准确性