首页 > 解决方案 > 可选字段上的 Redux-form 异步验证

问题描述

问题:

如果我没有从 asyncValidate 函数传递一个承诺,它asyncValidation.js:8 Uncaught Error: asyncValidate function passed to reduxForm must return a promise也会失败,我如何访问传递给asyncValidat函数 失败验证图像中的组件的道具。

我的情况:

该表单具有选择固定 URL 的选项,然后如果您想输入自定义 URL,您可以选择自定义复选框并在文本字段中输入 URL。我需要验证输入的自定义 URL。

只有当用户选择输入自定义 URL 时,该字段才有值。当您在我的自定义 URL 文本字段中发送值时,它可以正常工作。当我不向字段发送值时,提交失败并出现上述错误

异步验证器的代码:

const asyncValidate = values => {
  const { custom_url } = values;
  const noFeedError = { custom_url: "No feeds found" };
  const fetchFailedError = { custom_url: "Fetch failed, try again" };

  if (custom_url && custom_url !== "") {
    return fetchOnlineFeeds(custom_url) //fetches if URL is valid fails with 503 
      .then(feedResult => {
        if (feedResult.error) {
          throw noFeedError;
        }
      })
      .catch(() => {
        throw fetchFailedError;
      });
  }
};

搜索并发现:

但似乎没有任何效果,如果我们必须以其他方式回报承诺,那么最好的方法是什么

标签: reactjsreduxredux-form

解决方案


我认为的问题是您在 if 之外返回未定义,尝试重构以以任何一种方式返回承诺

在你的 if 之后返回Promise.resolve(),你也可以猜猜return new Promise()

const asyncValidate = values => {
  const { custom_url } = values;
  const noFeedError = { custom_url: "No feeds found" };
  const fetchFailedError = { custom_url: "Fetch failed, try again" };

  if (custom_url && custom_url !== "") {
    return fetchOnlineFeeds(custom_url) //fetches if URL is valid fails with 503 
      .then(feedResult => {
        if (feedResult.error) {
          throw noFeedError;
        }
      })
      .catch(() => {
        throw fetchFailedError;
      });
  }
  return Promise.resolve();
};

推荐阅读