我是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();
}, [])
最佳答案
这是关于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/