首页 > 解决方案 > Redux-form 异步验证,避免使用“throw”

问题描述

所以我使用 redux-form 并按照文档中的异步验证示例,一切正常,但我想避免使用 throw 来抛出对象,如下所示

throw {email:"Already exists"}

我曾尝试使用“SubmissionError”,但是当我抛出 SubmissionError 时,它会在 redux 中的“asyncErrors”中添加一个名为“errors”的对象,然后错误不会显示在字段下方,如果我只是像这样抛出它,它们就会显示出来 throw {email: “已经存在”} 下面是我使用 SubmissionError 的代码

import { SubmissionError } from 'redux-form/immutable';
import { doesUserExist } from '../../shared/endpoints/userEndpoint';

const asyncValidate = (values /*, dispatch */) => {
  return doesUserExist(values.get('email')).then((res) => {
    if (res.registered) {
      throw new SubmissionError({ email: 'This email is already in use.' });
    }
  });
};

export default asyncValidate;

输出 redux 状态是 -

form: {
registerForm:{
 asyncErrors:{
  errors:{email: "This email is already in use."}
  }
 }
}

标签: javascriptreactjsreduxredux-form

解决方案


如文档中所给出的SubmissionError,redux 中的表单将在对象中添加一般错误。asyncErrors

如果它被包含在表单 { field1: 'error', field2: 'error' } 中的错误的 redux-form SubmissionError 拒绝,那么提交错误将被添加到每个字段(到 error 属性),就像异步验证错误一样.

参考这里


推荐阅读