React Axios服务类

时间:2019-04-22 13:30:06

标签: javascript reactjs axios

我正在使用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包装器/服务类的示例可以简化它,而不必每次都编写相同的逻辑?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以轻松地使用一个小的咖喱函数:

 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);