【问题标题】:Redux-form async validation on optional field可选字段上的 Redux-form 异步验证
【发布时间】:2020-10-20 08:42:45
【问题描述】:

问题:

如果我没有从 asyncValidate 函数传递承诺,它会因asyncValidation.js:8 Uncaught Error: asyncValidate function passed to reduxForm must return a promise 而失败,我如何访问传递给asyncValidat 函数中的组件的道具 failed validation image.

我的情况:

表单具有选择固定 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;
      });
  }
};

搜索并找到:

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

【问题讨论】:

  • 看来你也有孤独感 };最后,检查是否在某处打开
  • 格式化问题更新了代码块,谢谢

标签: reactjs redux redux-form


【解决方案1】:

我认为问题是你在 if 之外返回 undefined,尝试重构以返回一个承诺

在你的 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();
};

【讨论】:

  • 最好的方法似乎是 Promise.resolve() ,需要更多上下文,但如果你需要该文件返回一个承诺,你不能让它有条件地返回一个承诺,然后在没有条件的情况下使用程序遇到返回的值是未定义的,所以可能会破坏那里的任何东西
  • @SantiagoRebella 嘿,您能否也回答问题的第二部分,以便我批准您的回答。我如何访问 asyncValidate 函数中的道具。在验证 URL 之前需要添加一些基于 props 的检查
  • @Ukie Docs 是你的朋友。 redux-form.com/8.3.0/docs/api/reduxform.md/… asyncValidate 函数有一个签名 (values, dispatch, props, burredField)。请尝试将 SO 问题限制为单个特定问题,而不是提出多个问题。
  • DrewReese 谢谢,以后我会尽量只回答一个问题。 @SantiagoRebella 感谢您的帮助
猜你喜欢
  • 2019-07-08
  • 2017-12-21
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 2022-06-23
  • 2023-03-10
相关资源
最近更新 更多