Formik FieldArray 错误消息 - React Native
Formik FieldArray error messages - React Native
我正在使用 Formik FieldArray
作为我的表单的一部分,并且想要显示错误消息,我可以通过 errors.familyMembers[0]
访问组件内的错误消息,看起来像
[{"first_name": "First Name is a required field", "last_name": "Last Name is a required field"}]
为了显示错误,我有 2 个部分需要提取错误消息
isInvalid={fieldName in errors.familyMembers[0] && touched[fieldName]}
<FormErrorMessage
message={errors.familyMembers[0][fieldName]}
isVisible={touched[fieldName]}
/>
问题是当组件最初呈现时 errors.familyMembers[0]
是 undefined
,这给了我错误
undefined is not an object (evaluating 'errors.familyMembers[0]')
有什么方法可以防范 undefined
并在可用时显示消息?希望这是有道理的
您可以使用Optional chaining
,例如:
isInvalid={errors?.familyMembers && fieldName in errors.familyMembers[0] && touched[fieldName]}
<FormErrorMessage
message={errors?.familyMembers?.[0][fieldName]}
isVisible={touched[fieldName]}
/>
The optional chaining operator (?.
) enables you to read the value of a
property located deep within a chain of connected objects without
having to check that each reference in the chain is valid.
我正在使用 Formik FieldArray
作为我的表单的一部分,并且想要显示错误消息,我可以通过 errors.familyMembers[0]
访问组件内的错误消息,看起来像
[{"first_name": "First Name is a required field", "last_name": "Last Name is a required field"}]
为了显示错误,我有 2 个部分需要提取错误消息
isInvalid={fieldName in errors.familyMembers[0] && touched[fieldName]}
<FormErrorMessage
message={errors.familyMembers[0][fieldName]}
isVisible={touched[fieldName]}
/>
问题是当组件最初呈现时 errors.familyMembers[0]
是 undefined
,这给了我错误
undefined is not an object (evaluating 'errors.familyMembers[0]')
有什么方法可以防范 undefined
并在可用时显示消息?希望这是有道理的
您可以使用Optional chaining
,例如:
isInvalid={errors?.familyMembers && fieldName in errors.familyMembers[0] && touched[fieldName]}
<FormErrorMessage
message={errors?.familyMembers?.[0][fieldName]}
isVisible={touched[fieldName]}
/>
The optional chaining operator (
?.
) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.