可以绑定对象数组的bind formik验证错误
我有一个包含两个字段的表单:布尔值和对象数组。 当布尔值为真时,则应需要数组。 并且数组有两个字符串字段,一个字段不需要。
验证schecma
const validationSchema = Yup.object().shape({
boolVal: Yup.boolean().required().nullable(),
arr: Yup.array().when('boolVal', {
is: true,
then: Yup.array(
Yup.object().shape({
str1: Yup.string().nullable(),
str2: Yup.string().required()
),
})
),
}),
})
initialValues
const formik = useFormik({
initialValues:
{
boolVal:false,
arr: [new MyObject()]
}
})
当我尝试为类似数组的特定元素呈现错误时,
formik.errors.arr[0]
我得到了此错误
未知的错误:对象无效,作为一个react子女(找到:带键{str2}的对象)。如果您打算渲染一个孩子的集合,请改用数组。
当我悬停在“ arr”上以查看它的类型时,它给了我
(属性)arr?:字符串|字符串[] | formikerrors< MyObject> []
当我使用此代码行渲染错误时,
{JSON.stringify(formik.errors.arr)}
它会显示我
{“ arr”:[{“ str2”:“需要str2”}]}
I have a form that contains two fields: boolean value and array of objects.
when the boolean value is true then the array should be required.
and the array have two string fields one is required and the other is not.
Validation Schecma
const validationSchema = Yup.object().shape({
boolVal: Yup.boolean().required().nullable(),
arr: Yup.array().when('boolVal', {
is: true,
then: Yup.array(
Yup.object().shape({
str1: Yup.string().nullable(),
str2: Yup.string().required()
),
})
),
}),
})
initialValues
const formik = useFormik({
initialValues:
{
boolVal:false,
arr: [new MyObject()]
}
})
when i try to render the error for a specific element of the array like this
formik.errors.arr[0]
i got this error
Uncaught Error: Objects are not valid as a React child (found: object with keys {str2}). If you meant to render a collection of children, use an array instead.
and when i hover over the 'arr' to see the type of it, it gives me
(property) arr?: string | string[] | FormikErrors < MyObject > []
when i render the errors using this line of code
{JSON.stringify(formik.errors.arr)}
it shows me
{ "arr" : [ { "str2": "str2 is required" } ] }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我面临类似的问题,但我使用
getin
解决了它。您可以通过以下方式使用:
引用formik文档: https://formik.org/docs/api/fieldarray#fieldarray-validation-gotchas
I was facing a similar issue but I solved it using
getIn
.You can use it by following:
To refer formik documentation:https://formik.org/docs/api/fieldarray#fieldarray-validation-gotchas