所以我想列出一个联系人列表,这是代码:
Yup模式:
export const Schema = Yup.object().shape({
/**other fields */
contacts: Yup.array().required('Required field').of(
Yup.object().required('Required!').shape({
id: Yup.number(),
name: Yup.string().required('Required field!'),
phone: Yup.string().required('Required field!'),
email: Yup.string().email('Type a valid Email!').required('Required field!')
})
)})
Formik组件:
const Form = () => {
return (
<View>
<Formik
validationSchema={Schema}
initialValues: {
/* other values */
contacts: [
{
id: 0,
name: '',
phone: '',
email: ''
}
]
}
>
{({ handleChange, handleBlur, handleSubmit, setFieldValue, errors, touched, values }) => {
function addNewContact() {
setFieldValue('contacts', [
...values.contacts,
{ id: values.contacts[values.contacts.length - 1].id + 1, name: '', phone: '', email: '' }
])
}
return (
/**A lot of inputs here*/
{values.contacts.map(({ id, email, name, phone }, index) => (
<View key={id}>
<Text>Name *</Text>
<Input
value={name}
onChangeText={handleChange(`contacts[${index}].name`)}
onBlur={handleBlur(`contacts[${index}].name`)}
/>
{(errors.contacts ? errors.contacts[index].name : false)
&& (touched.contacts ? touched.contacts[index].name : false)
&& <Text>{`${errors.contacts[index].name}`}</Text>}
/**Repeat the above with phone and email */
</View>
))}
)
}}
</Formik>
</View>
)}
export default Form
我的问题是显示错误时,我无法访问它们。按照以上所述,intellisense表示name
中的errors.contacts[index].name
在类型string | FormikErrors<IContactProps>
我试图删除三元运算符条件,但它告诉我联系人可能未定义。
当我console.log(errors.contacts)
时,它显示了我可以通过errors.contacts[index].name
访问的数组。
即使出现该智能错误,我的代码也可以运行并与1位联系人一起工作。当我添加2个或更多联系人时,
当我在输入文本上输入undefined is not an object (evaluating errors.contacts[index].name)
如何正确访问对象数组上的这些错误?感谢您的帮助!
答案 0 :(得分:0)
我用其他方式解决了问题,而不是理想的方式。
{errors.contacts && errors.contacts[index] && Object.values(errors.contacts[index]).map((err, j) => (
<Text key={j + id}>{err}</Text>
))}
我将此放在View key={id}
下面。因此,我没有在联系人的每个字段中显示错误,而是在输入上方同时显示了所有错误。
如果有人知道如何解决上一个问题,我将很高兴。谢谢!
答案 1 :(得分:0)
对于正在寻找解决方案的任何人,我都可以肯定这是一个错误:https://github.com/formium/formik/issues/2347