我有一个简单的注册表,使用react-hook-form
和react-router
。我想在onSubmit
内重定向后,Axios后的请求。我不能使它发生,我不能找到任何在线解释为什么。
我已经从react-router
尝试了redirect
和useNavigate
。redirect
没有任何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>
);
}
1条答案
按热度按时间juud5qan1#
redirect
实用函数只在数据路由器(在'react-router@6.4中引入)中工作,并且只在路由loader或action函数中工作,而不在React组件中工作。在这种情况下,您应该使用
useNavigate
挂接。React挂接只能从React函数组件和自定义React挂接调用,不能在任何回调中调用。有关详细信息,请参阅Rules of Hooks。使用挂接返回的navigate
函数发出命令性重定向。示例: