未抓到(承诺){电子邮件:“电子邮件已存在”}

时间:2018-08-13 15:09:30

标签: reactjs redux fetch redux-form

因此,我尝试在我的redux-form(v7.3.0)输入字段中实现asyncValidation。如果电子邮件已经存在并且我正在使用check_email api调用后端,则后端的fetch函数将返回true。 api调用成功,并根据输入的电子邮件返回true或false,但与其在控制台中使用输入字段显示消息,不如在控制台中显示未捕获的错误。

asyncValidate.js文件

import { BASE_URL } from "../../config/apiConfig";
const asyncValidate = (values, dispatch, props) => {
      let opts = {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'client': localStorage.getItem('client'),
          'uid': localStorage.getItem('uid'),
          'access-token': localStorage.getItem('access-token')
        }
      };
      return fetch(`${BASE_URL}admin/users/check_email?email=${values.email}`, opts)
        .then((res) => {
          if(!res.ok){
            throw { email: "Something went wrong. Please Type Email again!" }
          }
          else{
            res.json().then((jsonRes) => {

              if (jsonRes) {
                throw { email: "Email already taken!" }; 
              }
            });
          }
        })
        .catch(error => {
          throw error
        });
    };

    export default asyncValidate;

docs所示,演示验证有效,当验证失败但上面给出的验证在控制台中引发未捕获的错误时,错误消息将在输入字段中显示。

1 个答案:

答案 0 :(得分:0)

问题出在then块中的else方法。 throw语句位于2个promise中,并且redux-form期望它位于单个promise中。因此,我将其更改为async/await语法。 最终代码如下所示。

import { BASE_URL } from "../../config/apiConfig";

const asyncValidate = (values, dispatch, props) => {
  let opts = {
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'client': localStorage.getItem('client'),
      'uid': localStorage.getItem('uid'),
      'access-token': localStorage.getItem('access-token')
    }
  };
  return fetch(`${BASE_URL}admin/users/check_email?email=${values.email}`, opts)
    .then(async (res) => {
      if(!res.ok){
        throw { email: "Something went wrong. Please Type Email again!" }
      }
      else{
        const jsonRes = await res.json();
        if(jsonRes) {
          throw { email: "Email already taken!" };
        }    
      }
    });
};

export default asyncValidate;