下面的函数异步获取帖子列表,并将接收到的数据发送到我的应用程序的Redux存储中。
该功能既可以处理原始帖子集的获取,也可以处理用户可以通过单击“加载更多”按钮触发的后续帖子。
export const fetchFilteredPosts = (filter, reset) => async(dispatch, getState, api) => {
if (reset) {
dispatch({
type: 'RESET_FILTERED_POSTS'
});
}
dispatch({
type: 'IS_FETCHING_FILTERED_POSTS'
});
try {
const currentPage = getState().filteredPosts.currentPage;
const nextPage = currentPage == 0 ? 1 : (currentPage + 1);
const filteredPosts = await api.get('/wp-json/wp/v2/posts?tag=' + filter + '&page=' + nextPage);
dispatch({
type: 'HAS_FETCHED_FILTERED_POSTS',
payload: {
data: filteredPosts.data,
currentPage: nextPage
}
});
} catch (error) {
dispatch({
type: 'FAILED_FETCHING_FILTERED_POSTS',
payload: error
});
}
}
这是我的Redux商店:
import { filteredPostsPerPage } from '../config';
const initState = {
canFetchMore: false,
currentPage: 0,
data: null,
fetchingError: null,
isFetching: null,
perPage: filteredPostsPerPage
}
export default (state = initState, action) => {
switch (action.type) {
case 'IS_FETCHING_FILTERED_POSTS':
return {
...state,
isFetching: true,
fetchingError: false
}
case 'HAS_FETCHED_FILTERED_POSTS':
const posts = action.payload.data;
return {
...state,
data: state.data === null ? posts : state.data.concat(posts),
isFetching: false,
canFetchMore: posts.length >= state.perPage,
currentPage: action.payload.currentPage
}
case 'FAILED_FETCHING_FILTERED_POSTS':
return {
...state,
isFetching: false,
fetchingError: action.payload
}
case 'RESET_FILTERED_POSTS':
return initState;
default:
return state;
}
}
假设我将10个设置为每页显示的帖子数,并且用户选择了一个类别,其中恰好有10个帖子。如果他们要单击“加载更多”按钮,则应用程序将引发以下错误:
{
"code": "rest_post_invalid_page_number",
"message": "The page number requested is larger than the number of pages available.",
"data": {
"status": 400
}
}
如何在函数的catch
部分中监听此确切错误,以便向用户显示一条消息,例如No more posts in this category
?我想我需要访问API请求的响应,但是我不确定在这种情况下该怎么做。
答案 0 :(得分:1)
您不能听特定的错误,必须听所有。 您可以使用if语句:
try {
/* ... */
} catch (e) {
if (e.data.status === 400) {
/* handle your error */
} else {
}
}
答案 1 :(得分:0)
找到了。这与使用Axios库有关,我没有提到我正在使用,因为我不知道在Axios中需要使用error.response
,而不仅仅是error
。因此,如果您使用Axios,则可以按以下方式捕获错误:
try {
/* ... */
} catch (error) {
if (error.response.data.status === 400) {
/* handle your error */
} else {
}
}