reactjs - 可选字段上的 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;
});
}
};
搜索并发现:
- https://github.com/redux-form/redux-form/issues/1166
- https://github.com/redux-form/redux-form/issues/1297
但似乎没有任何效果,如果我们必须以其他方式回报承诺,那么最好的方法是什么
解决方案
我认为的问题是您在 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();
};
推荐阅读
- ibm-midrange - 如何保留在 Subfile 上按下 Enter 和在 Popup 上按下 F5 的值
- javascript - 无法使用方法(传递)索引作为参数从数组中检索数据
- metal - 对金属中 mipmap 的生成感到困惑?
- python - 如何正确写入带有 fout 功能的输出?
- database - 未找到实体时的正确错误处理
- apache-spark - Spark抛出AnalysisException:未定义的函数:内置函数的“计数”
- django - AUTH_USER_MODEL 是指尚未为自定义身份验证后端安装的模型“base.User”
- nginx - 如何修复 Kubernetes Ingress Controller 切断集群中的节点
- unity3d - 如何更改 HDRP 材质着色器类型中的材质偏移?
- c++ - 如何将 std::function 的零个或多个参数用作 std::map 中的值?