我在我的React应用程序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);
}
}
Bellow是动作创建者:
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,
}
}
问题:在reducer中没有得到错误的问题可能是什么?
您可以使用.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) );