渲染值的反应验证问题

React validation issue for render value

我正在使用 React Yup 验证,但在编辑某些内容时遇到验证问题(编辑表单)。即使字段已填充,验证器的行为也像它们是空的一样。我已经记录了状态并且值也出现在那里..相同的代码在没有 value={contactPersonName || ""} 参数的情况下工作正常......参考附图

import React from "react";
import { Formik, Field, Form, ErrorMessage } from "formik";
import * as Yup from "yup";
import MaintanaceRequestService from "../../service/tenant/MaintanaceRequestService";
import axios from "axios";
import { CheckSquare } from "react-feather";
import {
  Card,
  CardHeader,
  CardTitle,
  CardBody,
  Button,
  FormGroup,
  Col,
} from "reactstrap";

const formValidation = Yup.object().shape({
  contactPersonName: Yup.string().nullable().required("Required"),
  priority: Yup.number().required("Required"),
  contactPersonEmail: Yup.string()
    .email("Invalid email address")
    .required("Required"),
});

class MaintananceUpdate extends React.Component {
  state = {
    successAlert: true,
  };

  async componentDidMount() {
    let mess = "";
    await axios
      .post("http://localhost:8080/tenant/maint/preEdit/", {
        maintId: "1144",
      })

      .then((response) => {
        console.log(response.data.maintReq);
        mess = response.data.maintReq;

        this.setState({
          updatable: true,
          contactPersonName: mess.contactPersonName,
          contactPersonEmail: mess.contactPersonEmail,
        });
      });
  }

  render() {
    const { contactPersonName, contactPersonEmail } = this.state;

    return (
      <Card>
        <CardHeader>
          <CardTitle>Maintanance Request</CardTitle>
        </CardHeader>
        <CardBody>
          <Formik
            initialValues={{
              contactPersonEmail: "",
              contactPersonName: "",
            }}
            validationSchema={formValidation}
            onSubmit={(values, actions) => {
              values.issueType = values.issueType.value;

              console.log(values.priority);
              setTimeout(() => {
                MaintanaceRequestService.createRequest(values).then(
                  (response) =>
                    this.setState({
                      description: response.data.description,
                    })
                );
                console.log(values);

                this.successMessgae("successAlert", true);
                actions.setSubmitting(false);
              }, 1000);
            }}
          >
            {(props) => {
              const { handleSubmit, setFieldValue, handleBlur } = props;
              return (
                <Form onSubmit={props.handleSubmit}>
                  <FormGroup>
                    <label htmlFor="contactPersonName">Person Name</label>
                    <Field
                      className="form-control"
                      name="contactPersonName"
                      placeholder="Doe"
                      type="text"
                      value={contactPersonName || ""}
                      onChange={(e) =>
                        this.setState({ contactPersonName: e.target.value })
                      }
                      onBlur={handleBlur}
                    />
                    <ErrorMessage
                      name="contactPersonName"
                      component="div"
                      className="field-error text-danger"
                    />
                  </FormGroup>
                  <FormGroup>
                    <label htmlFor="contactPersonEmail">Email</label>
                    <Field
                      className="form-control"
                      name="contactPersonEmail"
                      placeholder="jane@acme.com"
                      type="email"
                      value={contactPersonEmail || ""}
                      onChange={(e) =>
                        this.setState({ contactPersonEmail: e.target.value })
                      }
                      onBlur={handleBlur}
                    />

                    <ErrorMessage
                      name="contactPersonEmail"
                      component="div"
                      className="field-error text-danger"
                    />
                  </FormGroup>

                  <FormGroup row>
                    <Col md={{ size: 8, offset: 4 }}>
                      <Button.Ripple
                        color="primary"
                        type="submit"
                        className="mr-1 mb-1"
                      >
                        <CheckSquare size={14} />
                        <span className="align-middle ml-25">Submit</span>
                      </Button.Ripple>
                    </Col>
                  </FormGroup>
                </Form>
              );
            }}
          </Formik>
        </CardBody>
      </Card>
    );
  }
}
export default MaintananceUpdate;

Image

您正在使用自己的 handleChange。因此,一旦您完成了 handleChange 中的操作,请调用 formik 的 handleChange。除非您调用 formik 的 handleChange,否则 formik 不会知道您的 Field

上的更改
...
const { handleSubmit, setFieldValue, handleBlur, handleChange } = props; // <----------- destructure formik's handleChange
return (
<Form onSubmit={props.handleSubmit}>
    <FormGroup>
        <label htmlFor="contactPersonName">Person Name</label>
        <Field
            className="form-control"
            name="contactPersonName"
            placeholder="Doe"
            type="text"
            value={contactPersonName || ""}
            onChange={(e) =>
            {
                this.setState({ contactPersonName: e.target.value })
                handleChange(e) // <----------- call formik's handleChange
            }
            }
            onBlur={handleBlur}
        />

为 formik 添加 enableReinitialize 解决了我的问题

<Formik
          enableReinitialize
          ..
          render={
            ({
              ..
            }) => ( 
             //form uses initialValues
          )} />