【问题标题】:Formik handleSubmit is not getting calledFormik handleSubmit 没有被调用
【发布时间】:2023-01-24 00:33:45
【问题描述】:

我正在尝试在使用 formik 和 yup 验证提交之前验证表单。表单由两部分组成,第一个表单被验证然后加载下一个。并且正在设置状态 handleShow(true) 以触发第二种形式。下面是我的代码

  const UserOnboardSchema = Yup.object().shape({
    gender: Yup.string().required('please select the gender'),
    firstName: Yup.string().required('Please enter your first name'),
    lastName: Yup.string().required('Please enter your last name'),
    mobile: Yup.string()
      .required('Please enter your mobile number')
      .matches(phoneRegExp, 'Please enter valid phone number'),
    workExperience: Yup.string().required('Please enter your work experience'),
  });



  const formik = useFormik({
    initialValues: {
      gender: '',
      firstName: '',
      lastName: '',
      mobile: '',
      workExperience: '',
      currentRole: '',
    },
    validationSchema: UserOnboardSchema,
    onSubmit: (values) => {
      console.log(values);
      formik.resetForm();
    },
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    formik.handleSubmit();

    if (Object.entries(formik.errors).length === 0) {
      handleShow(true);
    } else {
      handleShow(false);
    }
  };

这是 handleSubmit 中的问题,formik.handleSubmit 不工作。它直接访问 if/else 条件,从而在不验证第一个表单的情况下加载第二个表单。

    if (Object.entries(formik.errors).length === 0) {
      handleShow(true);
    } else {
      handleShow(false);
    }

但如果我直接将handleShow(true) 给 formik,就像这样

  const formik = useFormik({
    initialValues: {
      gender: '',
      firstName: '',
      lastName: '',
      mobile: '',
      workExperience: '',
      currentRole: '',
    },
    validationSchema: UserOnboardSchema,
    onSubmit: (values) => {
      console.log(values);

      handleShow(true); #----> Giving here.

      formik.resetForm();
    },
  });

然后 formik 和 Yup 验证工作。我无法弄清楚是什么导致了这个问题?

【问题讨论】:

  • 您还可以使用 touched 属性来查看是否有任何元素被聚焦。所以检查 formik.touched 是否至少有一个键,而 formik.error 没有键

标签: javascript reactjs next.js


【解决方案1】:

如果没有表格本身,很难看出问题所在。不过,这里有一些有用的故障排除提示......

如果表单中存在错误,Formik 将不会触发 onSubmit 方法。所以,我的目标是:

  1. 检查表格中是否有任何错误,
  2. 查看 initialValues 对象是否有任何未使用的字段

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2020-05-01
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多