首页 > 解决方案 > 数据直到减速器才到达

问题描述

我在我的反应应用程序 redux saga 中使用。我有一个登录表单。使用 redux saga,我尝试在用户登录时处理错误。贝娄是我的传奇:

function* postLoginUserReq(user) {
    const {name} = user.values.user;
    try {
        const data = yield call(() => {
            return fetch("url", {
                method: 'post',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                }),
            }).then(data => data.json()).then(response => {
                userErrorLogIn(response.error) //here i check if appears an error

            })
        });

    } catch (error) {
        console.log(error);
    }
}

贝娄是动作创造者:

export const userErrorLogIn = (error) => {
    console.log(error)  //the error message appears here
    return {
        type: USER_ERROR_LOGIN,
        payload: error
    };
};

波纹管是减速器:

 case USER_ERROR_LOGIN: {
            console.log(action.payload)  //here the error message does not appears (why?)
            return {
                ...state,
                userIsLoggedError:action.payload,
            }
        }

问题:我没有得到减速器错误的问题可能是什么?

标签: javascriptreactjs

解决方案


您可以为此使用 .catch -

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}
fetch("http://httpstat.us/500")
    .then(handleErrors)
    .then(response => console.log("ok") )
    .catch(error => userErrorLogIn(error) );

https://www.tjvantoll.com/2015/09/13/fetch-and-errors/


推荐阅读