无法从动作创建者调用动作功能

时间:2019-01-20 23:57:01

标签: reactjs redux redux-thunk

不幸的是,我无法从catch错误块内部调用handleApiErrors。未调用该函数,代码行handleApiErrors(error,'无法检索数据')被忽略)

双重使用调度似乎是造成问题的原因,但根据笨拙的文档,它应该可以工作

const getInitialData = () => (dispatch) => {
    getBookList()
        .then((books) => {
            dispatch(fetchBooksSuccess(books));
        })
        .catch((error) => {
            handleApiErrors(error, 'Data could not be retrieved') 
        });
    };


const handleApiErrors = (error, userMessage = '') => (dispatch) => {
    const { response, message } = error;
    let errorMessage = '';
    switch (response.status) {
        case 401:
            errorMessage = 'You are not authenticated';
            break;
        case 403:
            errorMessage = 'You are not authorized to access this ressource';
            break;
        case 500:
            errorMessage = `${userMessage} There was an internal error, please try again`;
            break;
        case 503:
            errorMessage = `${userMessage} The network connection is unavailable at the moment`;
            break;
        default:
            errorMessage = message;
     }
     dispatch(setApiErrors(errorMessage));
};

1 个答案:

答案 0 :(得分:0)

动作应该是简单的函数返回。

dispatch(handleApiErrors(error, 'Data could not be retrieved'));


const handleApiErrors = (error, userMessage = '') => {
const { response, message } = error;
let errorMessage = '';
switch (response.status) {
    case 401:
        errorMessage = 'You are not authenticated';
        break;
    case 403:
        errorMessage = 'You are not authorized to access this ressource';
        break;
    case 500:
        errorMessage = `${userMessage} There was an internal error, please try again`;
        break;
    case 503:
        errorMessage = `${userMessage} The network connection is unavailable at the moment`;
        break;
    default:
        errorMessage = message;
 }
 setApiErrors(errorMessage);
};