reactjs - 最终表单数组字段异步验证
问题描述
我正在尝试实现异步验证react-final-form-array
。但它的回报承诺但根本没有显示错误。
我参考了这段代码进行 asnyc 验证,并在此处使用最终表单数组创建了我自己的版本。
形式:
<Form
onSubmit={onSubmit}
mutators={{
...arrayMutators
}}
initialValues={{ customers: [{ placeholder: null }] }}
validate={formValidate}
render={({
handleSubmit,
mutators: { push, pop }, // injected from final-form-arrays above
pristine,
reset,
submitting,
values,
errors
}) => {
return (
<form onSubmit={handleSubmit}>
<div>
<label>Company</label>
<Field name="company" component="input" />
</div>
<div className="buttons">
<button type="button" onClick={() => push("customers", {})}>
Add Customer
</button>
<button type="button" onClick={() => pop("customers")}>
Remove Customer
</button>
</div>
<FieldArray name="customers" validate={nameValidate}>
{({ fields }) =>
fields.map((name, index) => (
<div key={name}>
<label>Cust. #{index + 1}</label>
<Field
name={`${name}.firstName`}
component={testInput}
placeholder="First Name"
/>
<Field
name={`${name}.lastName`}
component={testInput}
placeholder="Last Name"
/>
<span
onClick={() => fields.remove(index)}
style={{ cursor: "pointer" }}
>
❌
</span>
</div>
))
}
</FieldArray>
<div className="buttons">
<button type="submit" disabled={submitting || pristine}>
Submit
</button>
<button
type="button"
onClick={reset}
disabled={submitting || pristine}
>
Reset
</button>
</div>
<pre>
nameValidate Function:{"\n"}
{JSON.stringify(nameValidate(values.customers), 0, 2)}
</pre>
<pre>
Form errors:{"\n"}
{JSON.stringify(errors, 0, 2)}
</pre>
<pre>
Form values:{"\n"}
{JSON.stringify(values, 0, 2)}
</pre>
</form>
);
}}
/>
验证功能:
const duplicateName = async value => {
await sleep(400);
if (
~["john", "paul", "george", "ringo"].indexOf(value && value.toLowerCase())
) {
return { firstName: "name taken!" };
}
};
const nameValidate = values => {
if (!values.length) return;
const errorsArray = [];
values.forEach(value => {
if (value) {
let errors = {};
if (!value.firstName) errors.firstName = "First Name Required";
if (Object.keys(errors).length === 0) {
errors = duplicateName(value.firstName);
console.log("errors", errors);
}
errorsArray.push(errors);
}
});
return errorsArray;
};
解决方案
好的,您正在以一种不允许的方式混合验证。您不能在错误数组中嵌入 Promise,整个验证函数必须返回一个 Promise。这是固定版本。这await duplicateName()
是重要的一点。
const nameValidate = async values => {
if (!values.length) return
return await Promise.all(
values.map(async value => {
let errors = {}
if (value) {
if (!value.firstName) errors.firstName = 'First Name Required'
if (Object.keys(errors).length === 0) {
errors = await duplicateName(value.firstName)
}
}
console.error(errors)
return errors
})
)
}
推荐阅读
- amazon-web-services - route53 列表托管区域输出抛出“不支持索引”错误
- python - pandas csv到行和列的数据框转换
- nginx - 如何使用 nginx 服务器处理 vuejs SPA 中的 404 错误请求
- windows - 如何使用 msvc 14.0 在 Windows x64 上构建 Boost 1.65
- c# - 如何读取/显示文件中的“\n”文本作为换行符?
- c++ - 接受用户输入的整数只能限制为 1 位
- google-play-services - 如何自定义可以在 Playstore 中找到我的应用的单词?
- java - 寻找组合框但不是 Android 微调器
- javascript - 动态切弦
- powershell - 快捷方式未显示 TargetPath