Using setFieldValue onSubmit in Formik

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 06:35:41

问题


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.

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.

Here is my code and the demo:

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>
);

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


回答1:


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))
}}


来源:https://stackoverflow.com/questions/57208048/using-setfieldvalue-onsubmit-in-formik

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!