使用 useMutation 成功提交后,react 查询正在刷新钩子表单

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

我正在尝试在 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”的最后一个数据是由表单添加的。

reactjs react-hook-form react-query
1个回答
0
投票

我使用React Router中的useNavigate在成功突变后导航到不同的页面,并确保表单提交逻辑通过使用react-hook-form的handleSubmit正确处理它来阻止页面重新加载。

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>


import { useMutation } from "react-query";
import { useNavigate } from "react-router-dom"; // Import useNavigate
import CommonForm from "../components/commonform";
import axios from "axios";

// Mutation function to add user
const addUser = async (data) => {
  let res = await axios.post("http://localhost:1000/user", data);
  return res;
};

const CreateUser = () => {
  const navigate = useNavigate(); // Initialize useNavigate
  const { mutate } = useMutation(addUser, {
    onSuccess: () => {
      // Redirect to another page on success, e.g., "/users"
      navigate("/users");  // Use the route where you want to navigate
    },
    onError: (error) => {
      // Handle any errors if needed
      console.error("Error adding user:", error);
    }
  });

  const submitHandler = (data) => {
    console.log("Data submitted from the form", data);
    mutate(data); // Trigger mutation with form data
  };

  return (
    <div>
      <CommonForm view="createForm" submitHandler={submitHandler} />
    </div>
  );
};

export default CreateUser;



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"
        />
        {/* email validation message */}
        <br />
        <p>{errors.email?.message}</p>
        <br />

        <input type="submit" value="Submit" />
      </form>
    </div>
  );
};

export default CommonForm;

© www.soinside.com 2019 - 2024. All rights reserved.