我使用 Formik 在功能组件 ReactJS 上创建简单的表单。当组件挂载时,我的表单应该从 API 获取数据的输入字段。为此,我使用了 fetch 和 useEffect。获取后,从 API 中检索数据,但在触发 formik.handleChange 之前不会填充。
如果尝试在任何输入字段中指定某些内容,则会触发 formik.handleChange,并且所有字段都会立即填充来自 API 的数据(在我的情况下,只填充电子邮件)
当组件挂载时,我如何触发 formik.handleChange ?
import React, { useEffect } from 'react';
import { TextField, Button } from '@material-ui/core/';
import { useFormik } from 'formik';
import * as yup from "yup";
const validationSchema = yup.object({
Title: yup.string("Enter your Title").required("Title is required"),
email: yup
.string("Enter your email")
.email("Enter a valid email")
.required("Email is required"),
});
export default function Form() {
const formik = useFormik({
initialValues: {
Title: "",
email: ""
},
validationSchema: validationSchema,
onSubmit: async (values) => {
//...code of post function
//...code of post function
//...code of post function
}
});
useEffect(() => {
(async () => {
try {
let response = await fetch(
"https://run.mocky.io/v3/5be581aa-89d3-43e3-8478-7186633f8d16"
);
let content = await response.json();
formik.initialValues.email = content[0].email;
} catch (e) {
console.log(e);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<form onSubmit={formik.handleSubmit}>
<TextField
fullWidth
id="email"
name="email"
label="Email"
value={formik.values.email}
onChange={formik.handleChange}
error={formik.touched.email && Boolean(formik.errors.email)}
helperText={formik.touched.email && formik.errors.email}
/>
<Button color="primary" variant="contained" fullWidth type="submit">
Submit
</Button>
</form >
);
}
此外,我还有第二种使用 ReactState 的方法,但我认为这种方法不太受欢迎,但它还有另一个错误:获取后,状态填充了我的输入字段,但验证失败。当我尝试提交数据时,验证发送反应状态的默认值(那些在获取之前)