在Axois中获取错误,并且在派发值未获得道具后出现错误

问题描述 投票:1回答:2

我是Redux React的新手,正在创建Web应用程序,其中应用程序与Lumen API框架进行交互。当请求转到服务器并返回错误代码400、404、500时,除200以外的任何状态代码(错误)都会显示控制台错误,然后在React中进行处理。

我尝试在axois.catch({dispatch})处获取错误时传递值,但通过查看redux-dev-tool来更新状态值,但在props处未获取值。

从API开始,我像这样传递:

if ($validator->fails()) {
   return response()->json(['type'=> 'error','message'=> $validator->errors()->all()],400);
}

以及在我的动作文件中,例如:

export const loginRequest = formValues => async dispatch => {

await user.post('/user/create', { ...formValues, device_id: 12345}).then(response => {
  dispatch ({type: LOGIN, payload: response.data});
}).catch(error => {
  if(error.response) {
    dispatch ({ type: ERRORS, payload: error.response.data.message });
  }
});
}

和在减速器中:

const INTIAL_STATE = {
    isSignedIn: null,
    accessToken: null,
    loginMessage: null,
    errorMessage: null
};

export default (state = INTIAL_STATE, action) => {
switch (action.type){
    case ERRORS:
        return { ...state, isSignedIn: false, accessToken:null , errorMessage: action.payload };
    default:
        return state;
}
};

最后在我的组件文件中:

const mapStateToProps = state => {
  return {error: state.auth.errorMessage};
};

和控制台登录渲染方法:

console.log(this.props);

我在控制台中获得POST http://localhost:8000/user/create 500 (Internal Server Error),但errorMessage值的状态已更新,如在redux-dev-tool中查看的,并且在错误后没有代码运行。

reactjs redux axios lumen
2个回答
1
投票

使用redux-saga-routines进行分派操作,使用此模块可以使工作轻松。这里的文档链接https://github.com/afitiskin/redux-saga-routines


0
投票

等待更改异步以进行同步。因此,您不应该为此写承诺。因此,您可以将其更改为如下所示:

export const loginRequest = formValues => async dispatch => {
    try {
        const response = await user.post('/user/create', { ...formValues, device_id: 12345 });
        dispatch ({ type: LOGIN, payload: response.data });
    } catch (error) {
        if(error.response) {
            dispatch ({ type: ERRORS, payload: error.response.data.message });
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.