reduxForm未提交,给出错误Unhandled Rejection(SubmissionError):提交验证失败

时间:2018-10-26 09:59:27

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

我正在使用reduxForm 7.4.2,我想提交表单并显示服务器端验证错误,但这会给我以下错误:

enter image description here

服务器响应:

enter image description here

这是 LoginForm 组件:

import React,{Component} from 'react'
import InputGroup from '../ui/InputGroup';
import { bindActionCreators } from "redux"
import { Field , reduxForm,SubmissionError} from 'redux-form';
import {faEnvelope,faLock} from '@fortawesome/free-solid-svg-icons'
import { connect } from 'react-redux';
import { loginUser,loginUserFailure,loginUserSuccess } from '../../actions/authActions';


class LoginForm extends Component {
    constructor(){
        super();
        this.submitLoginForm=this.submitLoginForm.bind(this);
    }

    submitLoginForm=values=>{         
       this.props.loginUser(values);      
    }

    render() {
    const { handleSubmit, submitting} = this.props;
    return(
        <form onSubmit={handleSubmit(this.submitLoginForm)}>
                    <Field component={InputGroup} type="email" placeholder="Email" id="email" name="email" icon={faEnvelope}></Field>
                    <Field component={InputGroup} type="password" placeholder="Password" id="password" name="password" icon={faLock}></Field>
                    <button type="submit" className="btn btn-success btn-block" disabled={submitting}>Login</button>
        </form>
    )
  }
}

const mapStateToProps = (state, ownProps) => ({
    user:state.user
})


 const mapDispatchToProps = (dispatch) => {
   return bindActionCreators({
    loginUser,
    loginUserFailure,
    loginUserSuccess,
    }, dispatch)
  }

LoginForm = connect(mapStateToProps,mapDispatchToProps)(LoginForm);
LoginForm = reduxForm({ form: 'loginForm'})(LoginForm);
export default LoginForm;

src / actions / authActions

import axios from 'axios';
import { SubmissionError} from 'redux-form';


export const LOGIN_USER = 'LOGIN_USER';
export const LOGIN_USER_SUCCESS = 'LOGIN_USER_SUCCESS';
export const LOGIN_USER_FAILURE = 'LOGIN_USER_FAILURE';

export const loginUser =userdata=>{
   return dispatch => {
    try {
      const request = axios.post("/api/auth/login", userdata);
      request
        .then(res => {
          dispatch(loginUserSuccess(request));
        })
        .catch(e => {
          //dispatch(loginUserFailure(e));
          dispatch(loginUserFailure(e.response.data));
          throw new SubmissionError(e.response.data);
        });
    } catch (e) {
      dispatch(loginUserFailure(e));
    }
  }; 
 }

export const loginUserSuccess=user=>{
    return {
        type:LOGIN_USER_SUCCESS,
        payload:user
    }
}

export const loginUserFailure=error=>{
    return {
        type:LOGIN_USER_FAILURE,
        payload:error
    }
}

src / reducers / authReducer.js:

import { LOGIN_USER,LOGIN_USER_SUCCESS,LOGIN_USER_FAILURE} from './../actions/authActions';

const INITIAL_STATE = {isAuthenticated: false,user: null, status:null, error:null, loading: false};

  export default function(state = INITIAL_STATE, action) {
    let error;
    switch (action.type) {
        case LOGIN_USER:
        return { ...state, isAuthenticated: false,user: null, status:'login', error:null, loading: true}; 

        case LOGIN_USER_SUCCESS:
        return { ...state, isAuthenticated: true,user: action.payload.user, status:'authenticated', error:null, loading: false}; 

        case LOGIN_USER_FAILURE:
        error = action.payload.data || {message: action.payload.message};     
        return { ...state,isAuthenticated: false, user:null, status:'login', error:error, loading: false};

  default:
        return state;
    }
}; 

store.js

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const initialState = {};
const middleware = [thunk];

const store = createStore(
  rootReducer,
  initialState,
  compose(
    applyMiddleware(...middleware),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  )
);
export default store;

根部减速器

import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form'
import authReducer from './authReducer';

export default combineReducers({
    form: formReducer,
    auth:authReducer
});

1 个答案:

答案 0 :(得分:1)

您在这里做错了两件事。也许我错过了其他问题,但是我对这两个问题有把握:

在分派中绑定动作创建者,以便能够在dumbcomponent Drawer中分派动作。做这样的事情(仅更改部分,我正在编辑):

import { bindActionCreators } from "redux"
const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({
    loginUser,
    loginUserFailure,
    loginUserSuccess,
  }, dispatch)
}

您必须使用redux-thunk作为中间件。当将redux与react一起使用时,它用于处理异步调度。您的api调用是异步的,因此在进行axios post调用后,您无法直接返回响应。您需要以这种方式在此处返回一个函数:

export const loginUser = userdata => {
      return dispatch => {
        try {
          const request = axios.post("/api/auth/login", userdata);
          return request
            .then(res => {
              dispatch(loginUserSuccess(request));
            })
            .catch(e => {
              dispatch(loginUserFailure(e));
            });
        } catch (e) {
          dispatch(loginUserFailure(e));
        }
      };
    };

并删除哑组件中的promise处理。因为您的所有数据现在都可以在redux中使用,可以通过mapStateToProps获取。

注意:我可能没有打过花括号。请检查并欢迎反馈