【发布时间】:2020-11-19 10:17:51
【问题描述】:
我是 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和async/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