getIn 与 Formik 的作用是什么?

Jnl*_*Jnl 4 javascript typescript reactjs formik

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"
    />
))}
Run Code Online (Sandbox Code Playgroud)

小智 13

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');
Run Code Online (Sandbox Code Playgroud)

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

  • 这看起来是一个正确的答案。想知道为什么人们提出问题,然后对花时间回答问题的人没有任何反应(接受答案、点赞、评论……) (2认同)