react-router-dom报错navigate.push is not a function该如何解决?
问题原因
你遇到的navigate.push is not a function报错,是因为react-router-dom v6版本对路由跳转API做了不兼容调整:旧v5版本的useHistory返回的history对象支持.push()方法,但你现在使用的useNavigate是v6专属API,返回的navigate本身就是可直接调用的函数,不存在.push实例方法。
解决方案
把代码中所有navigate.push("/")的写法,替换为直接调用navigate("/")即可。
同时你提供的代码还漏了React的useState导入,需要补充,修正后的完整代码如下:
import { Link, useNavigate } from "react-router-dom"; import { useState } from "react"; import { auth } from "./firebase"; function Login() { const navigate = useNavigate(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const signIn = (e) => { e.preventDefault(); auth .signInWithEmailAndPassword(email, password) .then((auth) => { navigate("/"); }) .catch((error) => alert(error.message)); }; const register = (e) => { e.preventDefault(); auth .createUserWithEmailAndPassword(email, password) .then((auth) => { // 成功使用邮箱密码创建新用户 if (auth) { navigate("/"); } }) .catch((error) => alert(error.message)); }; }
- 普通跳转(对应原history.push):
navigate(路由路径) - 替换当前历史记录跳转(对应原history.replace):
navigate(路由路径, {replace: true}) - 回退上一页(对应原history.goBack):
navigate(-1)
内容的提问来源于stack exchange,提问作者Vishal Mishra
相关产品推荐
相关产品推荐

