在 Formik 中使用 setFieldValue onSubmit [英] Using setFieldValue onSubmit in Formik

查看:30
本文介绍了在 Formik 中使用 setFieldValue onSubmit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 formik@jbuschke/formik-antdreact-input-mask 一起使用.我有一个掩码 +7 (___) ___-__-__ 应用于其中一个输入,我需要解析它 onSubmit 以删除不必要的符号.

I'm using formik with @jbuschke/formik-antd and react-input-mask. I have a mask +7 (___) ___-__-__ applied to one of the inputs and I need to parse it onSubmit to remove unnecessary symbols.

我已经定义了一个 const changedValue,然后在 setFieldValue 中使用它,但我收到以下错误:

I've defined a const changedValue, which is then used in setFieldValue, but I get the following error:

Invariant Violation
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

这是我的代码和演示::>

const CloseForm = () => (
  <Formik
    initialValues={{ phone: "", email: "" }}
    onSubmit={(values, { setSubmitting, setFieldValue }) => {
      const changedValue = values.phone.replace(/\(|\)|\s|-/g, "");
      setTimeout(() => {
        setFieldValue("phone", changedValue);
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 400);
    }}
    validate={validatePhone}
  >
    {({ isSubmitting, values, handleChange }) => {
      return (
        <Form>
          <FormItem name="phone" label="Phone" required="true">
            <CustomInput
              mask="+7 (999) 999-99-99"
              name="phone"
              onChange={handleChange}
            />
          </FormItem>
          <FormItem name="email" label="Email">
            <Input name="email" />
          </FormItem>
          <SubmitButton type="primary" disabled={isSubmitting}>
            Submit
          </SubmitButton>
          <pre>{JSON.stringify(values, null, 2)}</pre>
        </Form>
      );
    }}
  </Formik>
);

我该如何解决这个问题?或者可能有更好的方法来使用 setFieldValue 来解析值?

How can I fix this problem? Or may be there is a better way to use setFieldValue to parse the value?

推荐答案

你可以修改你要提交的值而不改变字段,例如:

You can modify the value you are going to submit without changing the field, for example:

onSubmit={values => {
  const phone = values.phone.replace(/\(|\)|\s|-/g, "")
  const valuesToSend = { ...values, phone }

  alert(JSON.stringify(valuesToSend, null, 2))
}}

这篇关于在 Formik 中使用 setFieldValue onSubmit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆