[英]React Axios Service Class
我正在使用axios處理我的React / Redux應用程序中的API調用。 令牌是全局設置的。
這里有些例子:
// Add Post
export const addPost = postData => dispatch => {
dispatch(clearErrors());
axios
.post('/api/posts', postData)
.then(res =>
dispatch({
type: ADD_POST,
payload: res.data,
})
)
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data,
})
);
};
// Add Comment
export const addComment = (postId, commentData) => dispatch => {
dispatch(clearErrors());
axios
.post(`/api/posts/comment/${postId}`, commentData)
.then(res =>
dispatch({
type: GET_POST,
payload: res.data,
})
)
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data,
})
);
};
// Get posts
export const getPosts = () => dispatch => {
dispatch(setPostsLoading);
axios
.get('/api/posts')
.then(res =>
dispatch({
type: GET_POSTS,
payload: res.data,
})
)
.catch(err =>
dispatch({
type: GET_POSTS,
payload: null,
})
);
};
// Delete post
export const deletePost = id => dispatch => {
axios
.delete(`/api/posts/${id}`)
.then(res =>
dispatch({
type: DELETE_POST,
payload: id,
})
)
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data,
})
);
};
您能否告訴我,在可伸縮應用程序中處理此類API調用的最佳方法是什么? 也許,有一個Axios包裝器/服務類的示例可以簡化它,而不是每次都編寫相同的邏輯?
謝謝!
您可以輕松地使用一個小的咖喱函數:
const api = (url, type, errorType) => postData => dispatch => {
dispatch(clearErrors());
axios
.post(url, postData)
.then(res =>
dispatch({
type,
payload: res.data,
})
)
.catch(err =>
dispatch({
type: errorType,
payload: err.response.data,
})
);
};
然后可以用作:
export const addPost = api("api/post", ADD_POST, GET_ERRORS);
export const addComment = (postId, data) => api(`/api/posts/comment/${postId}`, ADD_COMMENT, GET_ERRORS)(data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.