reactjs 使用React-Hook-Form提交时重定向

h43kikqp  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(245)

我有一个简单的注册表,使用react-hook-formreact-router。我想在onSubmit内重定向后,Axios后的请求。我不能使它发生,我不能找到任何在线解释为什么。
我已经从react-router尝试了redirectuseNavigateredirect没有任何React,并且在使用navigate时出现以下错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

我发现了一个帖子,其中Hook-Form的维护者建议使用props.history.push("./my-route"),就像在'Step1'中使用here一样。但这对我不起作用。我不知道历史是从哪里来的。唯一起作用的是window.location.replace("/my-route"),但我一点也不喜欢这个解决方案。
有人能帮助我或解释为什么react-router方法不起作用吗?是因为钩形不受控制吗?
我的代码:

import axios from "axios";
import { useForm } from "react-hook-form";
import { redirect, useNavigate } from "react-router-dom";

export function Login() {
  const onSubmit = async (data) => {
    try {
      console.log(data);
      await axios.post("http://localhost:5000/signup", data);
      // window.location.replace("/my-route");
    } catch (error) {
      console.error("There was an error!", error);
    }
  };

 return (
    <div>
      <h1>Blah</h1>
      <h4>Signup</h4>
      <form key={1} onSubmit={handleSubmit(onSubmitSignup)}>
        <input
          {...register("email", { required: true, minLength: 1 })}
          placeholder="email"
        />
        <input
          type="password"
          {...register("password", { required: true, minLength: 1 })}
          placeholder="password"
        />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}
juud5qan

juud5qan1#

redirect实用函数只在数据路由器(在'react-router@6.4中引入)中工作,并且只在路由loaderaction函数中工作,而不在React组件中工作。
在这种情况下,您应该使用useNavigate挂接。React挂接只能从React函数组件和自定义React挂接调用,不能在任何回调中调用。有关详细信息,请参阅Rules of Hooks。使用挂接返回的navigate函数发出命令性重定向。
示例:

import axios from "axios";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";

export function Login() {
  const navigate = useNavigate(); // <-- access navigate function

  const onSubmit = async (data) => {
    try {
      console.log(data);
      await axios.post("http://localhost:5000/signup", data);
      navigate("/my-route", { replace: true }); // <-- redirect
    } catch (error) {
      console.error("There was an error!", error);
    }
  };

 return (
    <div>
      <h1>Blah</h1>
      <h4>Signup</h4>
      <form key={1} onSubmit={handleSubmit(onSubmitSignup)}>
        <input
          {...register("email", { required: true, minLength: 1 })}
          placeholder="email"
        />
        <input
          type="password"
          {...register("password", { required: true, minLength: 1 })}
          placeholder="password"
        />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}

相关问题