【问题标题】:Redux display error messages from Nodejs backendRedux 显示来自 Nodejs 后端的错误消息
【发布时间】:2019-01-08 01:16:51
【问题描述】:

每当我登录失败时,我想在警报中显示我从后端收到的错误消息:

我的登录按钮从我的 user.actions 触发此功能:

function login(username, password) {
    return dispatch => {
        dispatch(request({ username }));

        userService.login(username, password)
            .then(
                user => {
                    dispatch(success(user));
                    history.goBack();
                },
                error => {
                    dispatch(failure(error.toString()));
                    dispatch(alertActions.error(error.toString()));
                }
            );
    };

    function request(user) { return { type: userConstants.LOGIN_REQUEST, user } }
    function success(user) { return { type: userConstants.LOGIN_SUCCESS, user } }
    function failure(error) { return { type: userConstants.LOGIN_FAILURE, error } }
}

我的 alert.reducer 如下所示:

  import { alertConstants } from '../_constants';

export function alert(state = {}, action) {
  switch (action.type) {
    case alertConstants.SUCCESS:
      return {
        type: 'alert-success',
        message: action.message
      };
    case alertConstants.ERROR:
      return {
        type: 'alert-danger',
        message: action.message
      };
    case alertConstants.CLEAR:
      return {};
    default:
      return state
  }
}

在我的 App.js 中,我使用 mapStateToProps 收到此状态:

function mapStateToProps(state) {
    const { alert } = state;
    return {
        alert
    };
}

之后,我想显示带有警报消息的警报:

  {alert.message &&
                          alert(alert.message)
                        }

你能帮我解决这个问题吗?

【问题讨论】:

    标签: node.js reactjs error-handling redux


    【解决方案1】:

    您的动作/reducer 代码看起来不错,我认为可能是与道具名称和本机警报功能冲突。 您是否尝试过更改道具名称?比如:

    function mapStateToProps(state) {
      const { alert } = state;
      return {
        alertState: alert
      };
    }
    

    { alertState.message && alert(alertState.message) }
    

    【讨论】:

    • 成功了!谢谢!疯了,这只是这个小调整......:D
    猜你喜欢
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2018-04-07
    • 2011-06-07
    • 2017-08-21
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多