【问题标题】:Show errors received from my server with react-redux使用 react-redux 显示从我的服务器收到的错误
【发布时间】:2018-11-23 20:00:18
【问题描述】:

如果我对我的 API 执行所有身份验证请求 不是直接在 react-redux 的“handleSubmit”函数内部,而是在自定义 redux 操作中,我遇到了将服务器收到的任何错误作为回复显示的问题。

这是身份验证操作 (authActions.js):

export const loginUser = userData => dispatch => {
  axios
    .post("auth/local/signin")
    .then(res => {

      dispatch({
        type: SET_CURRENT_USER,
        payload: res
      });
    })
    .catch(err => {

      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      });
    });
};

authReducer.js

import { SET_CURRENT_USER } from "../actions/types";

const initialState = {
  isAuthenticated: false,
  user: {}
};

export default function(state = initialState, action) {
  switch (action.type) {
    case SET_CURRENT_USER:
      return {
        ...state,
        isAuthenticated: Object.keys(action.payload).length > 0,
        user: action.payload
      };

    default:
      return state;
  }
}

errorReducer.js

  import { GET_ERRORS, CLEAR_ERRORS } from "../actions/types";

    const initialState = {};

    export default function(state = initialState, action) {
      switch (action.type) {
        case GET_ERRORS:
          return action.payload;
        case CLEAR_ERRORS:
          return {};
        default:
          return state;
      }
    }

当时唯一想到的就是连接redux,还有redux-form这个组件,然后去通过“new SubmissionError(errors)”报一个可能的错误。但这不适用于第一次提交。

class SignInForm extends Component {

  handleSubmit = values => {
    const userData = {
      username: values.username,
      password: values.password
    };

    this.props.loginUser(userData);

    const { errors } = this.props;
    console.log(errors);

    errors.username = errors.user;

    if (errors) throw new SubmissionError(errors);
  };

  render() {
    const { valid, handleSubmit, submitting } = this.props;

    return (
      <View>
      ...
      </View>
    );
  }
}

const mapStateToProps = state => ({
  auth: state.auth,
  errors: state.errors
});

const form = reduxForm({
  form: "Login", 
  validate, 
  asyncValidate,
  asyncChangeFields: ["username"]
})(SignInForm);

export default connect(
  mapStateToProps,
  { loginUser }
)(form);

【问题讨论】:

    标签: reactjs react-native redux react-redux redux-form


    【解决方案1】:

    您可以使用 Promises 将结果传递回登录组件。现在您已进入登录组件,如果失败,您可以向用户显示错误。

    authActions.js

    export const loginUser = userData => dispatch => {
        return new Promise((resolve, reject) => {
            axios
            .post("auth/local/signin")
            .then(res => {
    
              dispatch({
                type: SET_CURRENT_USER,
                payload: res
              });
              return resolve();
            })
            .catch(err => {
              return reject(err);
            });
        });
    }
    

    signin.js (?)

    handleSubmit = values => {
        const userData = {
          username: values.username,
          password: values.password
        };
    
        this.props.loginUser(userData)
            .catch((err) => {
                this.setState({ errorMsg: err });
            });
    
    };
    
    render() {
        const { valid, handleSubmit, submitting } = this.props;
    
        return (
          <View>
              ...
              <div>Failed to login with error message: {this.state.errorMsg}</div>
          </View>
        );
    }
    

    【讨论】:

    • 您好! @Shawn Andrews 我认为这是一个非常优雅的解决方案,但我也认为它不能很好地与 react-redux 集成。因为例如,当我必须使用 SubmissionError 类生成验证错误时,我必须在 catch 块中执行此操作,但这会导致“未处理的承诺”错误。 throw new SubmissionError(errors);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2021-10-02
    • 2016-07-17
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多