Redux Forms submit validation does not set errors messages

I am trying to make form with submit validation. When I submit form, my handleSubmit fired and throw SubmissionError , but nothing happens any more.

Submit (just throw error every time):

function submit(values)
{
   console.log(values);
   throw new SubmissionError({ password: 'Wrong password', _error: 'Login failed!' });
}

Render field from example:

const renderField = ({ input, label, type, meta: { touched, error } }) => (
  <div>
    <label>{label}</label>
    <div>
     <input {...input} placeholder={label} type={type}/>
     {touched && error && <span>{error}</span>}
   </div>
  </div>
 )

My form:

class LoginForm extends Component {
  render()
  {
    const {  error, handleSubmit, pristine, reset, submitting  } = this.props
    console.log(error);
    return (
      <div>
        <form onSubmit={handleSubmit}>
          <h1>Login</h1>
          <Field name="email" type="text" component={renderField} label="Username"/>
          <Field name="password" type="text" component={renderField} label="Username"/>
           {error && <strong>{error}</strong>}
          <button type = "submit">Login</button>
        </form>
      </div>
     )
  }
}

LoginForm = reduxForm({
    form: 'login',
    onSubmit: submit
})(LoginForm);

export default LoginForm;

When I press Submit , the submit function is called, exception is thrown, but nothing happens else and errors message in form and renderField not shown.


You need to add a validation method to the reduxForm constructor like the following:

function validateInput(input) {
  let errors = {}

  if (!data.email) {
    errors.email = "Email is required."
  } 

  if (!data.password) {
    errors.password = "Password is required."
  }

  return errors 
}

const loginForm = reduxForm({
  form: 'login',
  onSubmit: submit,
  validate: validateInput
})

This will cause redux-form to show the errors under the input field if they are not valid.

Of course you need to connect your component with react-redux connect for this to work like this:

export default connect(mapStateToProps)(loginForm(LoginForm)) 

A throwable error that is used to return submit validation errors from onSubmit. The purpose being to distinguish promise rejection because of validation errors from promise rejection because of AJAX I/O problems or other server errors. docs

So, the purpose of SubmissionError is not to directly throw an error. Use this when you are doing some promise like API request ie

  return axios
     .post('/sessions/login', values)
     .then((res) => {
           // do something with response
     })
     .catch((err) => {
           throw new SubmissionError(err.response.data);
     });
链接地址: http://www.djcxy.com/p/93184.html

上一篇: 用.toFixed()指数级小数字

下一篇: Redux Forms提交验证不会设置错误消息