如何将我的错误消息从axios调用的服务器传递给我的组件

时间:2017-02-01 10:44:11

标签: reactjs redux react-redux axios

我对React真的很陌生。我在我的操作中有一个axios请求我希望我的错误消息传递给我有这个代码的组件:

    import axios from 'axios';
    import setAuthorizationToken from '../utils/setAuthorizationToken';
    import jwtDecode from 'jwt-decode';
    import { SET_CURRENT_USER, BASE_URL } from './types';

    const instance = axios.create({
      baseURL: BASE_URL
    });

    export function setCurrentUser(user) {
      return {
        type: SET_CURRENT_USER,
        user
      };
    }

    export function logout() {
      return dispatch => {
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        setAuthorizationToken(false);
        dispatch(setCurrentUser({}));
      }
    }

    export function login(data) {
      return dispatch => {
        return instance.post('/authenticate', data).then(function(response) {
          const token = response.data.accessToken;
          const refreshToken = response.data.refreshToken;
          localStorage.setItem('accessToken', token);
          localStorage.setItem('refreshToken', refreshToken);
          setAuthorizationToken(token);
          dispatch(setCurrentUser(jwtDecode(token)));
        })
        .catch(function(error){
          console.log('error: ', error.response.data);
        });
      }
    }

这是我的组件:

    import React from 'react';
    import TextFieldGroup from '../common/TextFieldGroup';
    import validateInput from '../../server/validations/login';
    import { connect } from 'react-redux';
    import { login } from '../../actions/authActions';

    class LoginForm extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          username: '',
          password: '',
          errors: {},
          isLoading: false
        };

        this.onSubmit = this.onSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
      }

      isValid() {
        const { errors, isValid } = validateInput(this.state);

        if (!isValid) {
          this.setState({ errors });
        }

        return isValid;
      }

      onSubmit(e) {
        e.preventDefault();
        if (this.isValid()) {
          this.setState({ errors: {}, isLoading: true });
          this.props.login(this.state).then(
            (res) => this.context.router.push('/'),
            (error) => this.setState({ errors: error.response.data , isLoading: false }),
          );

        }


      }

      onChange(e) {
        this.setState({ [e.target.name]: e.target.value });
      }

      render() {
        const { errors, username, password, isLoading } = this.state;

        return (
          <form onSubmit={this.onSubmit}>
            <h1>Login</h1>

            { errors.message && <div className="alert alert-danger">{errors.message}</div> }

            <TextFieldGroup
              field="username"
              label="Username"
              value={username}
              error={errors.username}
              onChange={this.onChange}
            />

            <TextFieldGroup
              field="password"
              label="Password"
              value={password}
              error={errors.password}
              onChange={this.onChange}
              type="password"
            />

            <div className="form-group"><button className="btn btn-primary btn-lg" disabled={isLoading}>Login</button></div>
          </form>
        );
      }
    }

    LoginForm.propTypes = {
      login: React.PropTypes.func.isRequired
    }

    LoginForm.contextTypes = {
      router: React.PropTypes.object.isRequired
    }

    export default connect(null, { login })(LoginForm);

这是console.log

  

错误:对象{代码:&#34;未经授权&#34;,消息:&#34;无效的用户名或密码。&#34;}

目前我不知道将错误消息传递给组件。我是React和Redux的新手

1 个答案:

答案 0 :(得分:2)

首先,您必须在reducer上添加初始状态。例如

<强> authReducer.js

const initialState = {
  ... // another state
  errors: {}
}

function yourReducer(state = initialState, action) {
  case 'SHOW_ERROR':
    return {
      ...state,
      errors: action.message
    }
  default:
    return state
}

登录操作时,发送&#39; SHOW_ERROR&#39;

<强> authActions.js

export function login(data) {
  return dispatch => {
    return instance.post('/authenticate', data).then(function(response) {
      ...
      // success
    })
    .catch(function(error){
    // fail
      dispatch({ type: 'SHOW_ERROR', message: error.response.data })
    });
  }
}

然后你需要将redux状态映射为组件上的道具

<强> LoginComponent.js

function mapStateToProps(state) {
  return {
    you: may.return.another.state.here,
    errors: state.yourReducerName.errors
  }
}

export default connect(mapStateToProps, { login })(LoginForm);

最后,您可以将errors称为组件

上的道具
class LoginForm extends React.Component {
  ...
  render() {
    const { errors, username, password, isLoading } = this.state;
    const { errors } = this.props // errors from redux state

    return (
      <form onSubmit={this.onSubmit}>
        <p>{errors.message}</p>
        <h1>Login</h1>
        ...
        <div className="form-group"><button className="btn btn-primary btn-lg" disabled={isLoading}>Login</button></div>
      </form>
    );
  }
}

不要忘记验证道具类型。祝你好运!