getIn在Formik中的作用是什么?

6
这里的getIn函数的作用是什么?它只是读取并从已定义的字段中分配值吗?
{fileds.map(({ formikRef, ...input }) => (
    <TextField
       key={formikRef}
       helperText={
       getIn(formik.touched, formikRef)
                    ? getIn(formik.errors, formikRef)
                    : ''
                }
       value={getIn(formik.values, formikRef)}
      {...input}
      variant="outlined"
      margin="normal"
    />
))}
1个回答

25

getIn是Formik中包含的一个实用函数。您可以使用它来通过路径从对象中提取深度嵌套的值。该路径使用点语法访问对象属性和方括号访问数组进行标注。

例如:

var exampleFormValues = {
  people: [
    {
      name: 'Alice',
      contactDetails: {
        email: 'alice@example.com',
        mobilePhone: '07123 456789'
      }
    },
    {
      name: 'Bob',
      contactDetails: {
        email: 'bob@example.com',
        mobilePhone: '07999 999999'
      }
    },
  ]
};

// this will return 'alice@example.com'
var emailOfFirstPerson = getIn(exampleFormValues, 'people[0].contactDetails.email');

基本上与lodash的get函数相同,文档在此处:https://lodash.com/docs/#get


3
看起来是一个正确的答案。不知道为什么有些人会提问题,但却对那些花时间回答的人毫无反应(不接受答案、点赞或评论等)。 - Ahmad
很棒的答案。这个实用函数的好处之一是,它所接受的路径字符串将与给定字段的FieldFieldArray名称属性完全相同。由于您可能已经有一个字符串来定位传递给formik组件的字段,因此它使得手动访问formik正在跟踪的深度嵌套字段变得容易。 - ericArbour

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接