【问题标题】:Formik + Yup accessing errors for nested valuesFormik + Yup 访问嵌套值的错误
【发布时间】:2019-05-07 21:50:29
【问题描述】:

我正在尝试同时使用 Formik 和 Yup 来验证我的用户数据,但是当我尝试访问嵌套值的错误(例如 address.line1)时,我收到一条错误消息,指出它未定义。如何使用 Formik 和 Yup 访问嵌套值的错误?

参见代码沙盒:https://codesandbox.io/s/ly027lklq7

【问题讨论】:

    标签: node.js reactjs formik yup


    【解决方案1】:

    查看您的代码,您似乎访问了错误的对象。你的条件是errors.line1 && touched.address.line1,但应该是errors.address && errors.address.line1 && touched.address.line1

    您的错误发生是因为 errors.address 最初不存在,因为 errors 在开始时是一个空对象。您可以通过console.log(errors)查看。

    我尝试使用这段代码并且它有效。 (https://codesandbox.io/s/4w83767610?fontsize=14)

    <Form>
      <Field name="firstName" placeholder="first Name" />
        {errors.firstName && touched.firstName ? (
          <div>{errors.firstName}</div>
        ) : null}
        <br />
    
      <Field name="address.line1" placeholder="line 1" />
        // changed the conditional and object access
        {errors.address && errors.address.line1 && touched.address.line1 ? (
          <span className="red">{errors.address.line1}</span>
        ) : (
          ""
        )}
        <br />
        <button type="submit">Submit</button>
    </Form>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-29
      • 2019-12-10
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 2019-12-27
      相关资源
      最近更新 更多