我正在尝试在 json-server 文件中添加一些数据。为此,我使用了钩子表单,并使用 useMutation 发布数据。我能够添加 json-server 文件,但问题是,成功插入后,页面会自动重新加载。我想在成功后导航到另一个页面,但无法这样做。您能指导我这样做并停止刷新吗?代码是:
CreateUser.jsx 页面
import CommonForm from "../components/commonform";
import { useMutation } from "react-query";
const addUser = async (data) => {
let res = await axios.post("http://localhost:1000/user", data);
return res;
};
const CreateUser = () => {
const { mutate } = useMutation(addUser);
const submitHandler = (data) => {
console.log("Data submitted from the form", data);
mutate(data);
};
return (
<div>
<CommonForm view="createForm" submitHandler={submitHandler} />
</div>
);
};
export default CreateUser;
CommonForm.jsx
import { useForm } from "react-hook-form";
const CommonForm = ({ view, submitHandler }) => {
const { register, handleSubmit, formState } = useForm();
const { errors } = formState;
return (
<div>
<form onSubmit={handleSubmit(submitHandler)} noValidate>
{/* username field with validation */}
<label htmlFor="uname">User Name: </label>
<input
type="text"
id="uname"
{...register("username", {
required: {
value: true,
message: "* User name is required",
},
minLength: {
value: 3,
message: "Minimum length 3",
},
})}
autoComplete="off"
/>
{/* username validation message */}
<br />
<p>{errors.username?.message}</p>
<br />
{/* email field with validation */}
<label htmlFor="email">Email : </label>
<input
type="email"
id="email"
{...register("email", {
required: {
value: true,
message: "* email is required",
}
})}
autoComplete="off"
/>
{/* error validation message */}
<br />
<p>{errors.email?.message}</p>
<br />
<input type="submit" value="Submit" />
</form>
</div>
);
};
export default CommonForm;
db.json 文件:
{
"user": [
{
"id": "1",
"username": "John Doe",
"email": "[email protected]"
},
{
"id": "22f8",
"username": "hello",
"email": "[email protected]"
}
]
}
最后一条数据“Hello”是表单添加的。
我使用 React Router 中的 useNavigate 在成功变异后导航到不同的页面,并确保表单提交逻辑通过使用 react-hook-form 的 handleSubmit 正确处理来防止页面重新加载。