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

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

问题描述

我正在将formik@jbuschke/formik-antdreact-input-mask一起使用.我对输入之一应用了掩码+7 (___) ___-__-__,我需要对其进行解析以删除不必要的符号.

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.

我已经定义了一个常量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天全站免登陆