Formik 不会更新状态给定的值

问题描述 投票:0回答:1

我正在使用 Metronic React Template 并自定义表单。我的一些表单字段的值被保存在一个状态中。当我提交包含填充输入的表单时,即使状态已更新,这些值也会作为空字符串返回。

这是我总结的代码:

const [currentPhoneNumber, setCurrentPhoneNumber] = useState("")

const handlePhoneNumberChange = (e) => {
    const asYouType = new AsYouType()
    const formatted = asYouType.input(e.target.value)

    setCurrentPhoneNumber(formatted)
}

const submitForm = async (values) => {
    console.log(values.phoneNumber) // returns "" when Field has value={currentPhoneNumber}
}

<Formik
    initialValues={initValues}
    validationSchema={schemas[currentSchemaIndex]}
    onSubmit={submitForm}
    enableReinitialize
>
    {() => (
        <Form
            className="py-20 w-100 w-xl-700px px-9"
            noValidate
            id="kt_create_account_form"
            placeholder={undefined}
        >
            // Not working
            <Field
                className="form-control form-control-lg form-control-solid"
                onChange={handlePhoneNumberChange}
                value={currentPhoneNumber}
                name="phoneNumber"
            />

            // Working
            <Field
                className="form-control form-control-lg form-control-solid"
                name="phoneNumber"
            />
        </Form>
    )}
</Formik>

在类似的问题中,enableReinitialize 属性可以解决问题,但不适合我。

reactjs formik metronic
1个回答
0
投票

使用formik时不需要给出任何状态。因为 formik 处理它自己的状态。那么就需要使用formik的方法来更新。这里是您的代码的固定版本:

import React from 'react';
import { Formik, Field, Form, setFieldValue } from 'formik';
import { AsYouType } from 'path'

export const AnyComponent = () => {
  return (
    <Formik
      initialValues={{currentPhoneNumber: ''}}
      validationSchema={schemas[currentSchemaIndex]}
      onSubmit={submitForm}
      enableReinitialize
    >
    {(props) => (
        <Form
            className="py-20 w-100 w-xl-700px px-9"
            noValidate
            id="kt_create_account_form"
            placeholder={undefined}
        >
            // Not working
            <Field
                className="form-control form-control-lg form-control-solid"
                onChange={(e) => {
                  const asYouType = new AsYouType();
                  const formatted = asYouType.input(e.target.value);
                  setFieldValue("currentPhoneNumber", formatted)
                }}
                value={props.values.currentPhoneNumber}
                name="phoneNumber"
            />

            // Working
            <Field
                className="form-control form-control-lg form-control-solid"
                name="phoneNumber"
            />
        </Form>
      )}
    </Formik>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.