我有一个Formik表单,在布局中使用react引导,为验证使用yup,如下所示:
import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { useParams } from "react-router-dom";
import { Formik, Field } from "formik";
import * as Yup from 'yup';
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
const VehicleForm2 = ({ action = "create" }) => {
const history = useHistory();
const VehicleValidationSchema = Yup.object().shape({
vehicleMake: Yup.string()
.required('Vehicle Make is required'),
vehicleModel: Yup.string()
.required('Vehicle Model is required')
});
const [initialValues, setValues] = useState({
vehicleMake: "",
vehicleModel: ""
});
const { id = "" } = useParams();
const handleSubmit = async (values) => {
var receivedData = "";
console.log("ENTERED SUBMIT METHOD");
try {
if (action === "create") {
await axios.post(`${process.env.REACT_APP_BASE_URL}/vehicle/add`, {
...values,
}).then(function (response) {
receivedData = response.data.Message;
});}
else {
await axios.patch(
`${process.env.REACT_APP_BASE_URL}/vehicle/edit/${id}`,
{
...values
}
);
}
history.push({pathname: '/vehicles',
state: { message: receivedData }
});
} catch (error) { console.log(error)}
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
validationSchema={VehicleValidationSchema}
render={({handleChange, handleSubmit, handleBlur, values, errors}) => (
<Form onSubmit={handleSubmit}>
<Row>
<Col>
<Form.Label>Make</Form.Label>
<Form.Control type="text" name="make" defaultValue={initialValues.make} placeholder="Enter make" />
</Col>
<Col>
<Form.Label>Model</Form.Label>
<Form.Control type="text" name="vehicleModel" defaultValue={initialValues.vehicleModel} placeholder="Enter vehicle model" />
</Col>
<Row>
<Button variant="primary" type="submit" style={{ width: "50%", margin: "auto" }}>
{action === "create" ? "Create Vehicle" : "Edit Vehicle"}
</Button>
</Row>
</Form>
)}
/>
在加载“编辑车辆”表单时,所有字段都将按预期填充。但是,当我更改字段的值并按Submit按钮时,似乎没有输入handleSubmit函数(因为handleSubmit()函数顶部的控制台日志没有打印)。相反,该页只是重新加载和显示原始值,而不是更改。
另外,在清除输入并将选项卡显示到下一个输入时,验证不会启动。
你能帮我找出我做错了什么吗?
谢谢。
发布于 2022-09-28 15:18:14
我认为验证失败了,因为您正在寻找vehicleMake
,而不是通过了make
。
const [initialValues, setValues] = useState({
vehicleMake: "",
vehicleModel: ""
});
<Form.Control type="text" name="make" defaultValue={initialValues.make} placeholder="Enter make" />
所以我认为你需要更新name="vehicleMake"
和initialValues.vehicleMake
发布于 2022-10-02 19:38:48
您试过在表单上删除onSubmit
吗?您只需要将onSubmit
添加到Formik
提供程序
<Formik onSubmit={handleSubmit}>
<Form>
</Form>
</Formik>
如果上面的内容不起作用,请尝试使用来自formik
的表单。例如:
import Formik, {Form} from "formik"
import BootstrapForm from "react-bootstrap/Form"
...
<Formik onSubmit={handleSubmit}>
<Form>
<Row>
<Col>
<BootstrapForm.Label>Make</BootstrapForm.Label>
...
</Col>
</Row>
</Form>
</Formik>
https://stackoverflow.com/questions/73888507
复制