如何修复React Router中「Property 'push' does not exist on type 'NavigateFunction'」错误?
错误原因
你遇到的问题是因为React Router v6 彻底重构了路由跳转API:在v5版本中我们通过useHistory获取history对象,用history.push()实现跳转;但v6的useNavigate返回的NavigateFunction是一个可直接调用的函数,不再包含push属性,因此TypeScript会抛出该错误。
解决方法
直接调用navigate函数并传入跳转参数即可,无需.push后缀:
import { useNavigate, useState, ChangeEvent } from "react-router-dom"; export function HomeScreen() { // 为useState指定类型,符合TypeScript规范 const [text, setText] = useState<string>(""); const navigate = useNavigate(); // 为事件参数指定类型 const handleChange = (e: ChangeEvent<HTMLInputElement>) => { setText(e.target.value); }; const handleClick = () => { // 直接调用navigate传入跳转配置 navigate({ pathname: '/Contact', state: { text: text } }); }; // 补充组件渲染逻辑示例 return ( <div> <input value={text} onChange={handleChange} /> <button onClick={handleClick}>跳转到联系页</button> </div> ); }
额外说明
- 默认调用
navigate()就是push行为(添加新历史记录);如果需要替换当前历史记录(对应v5的history.replace()),可传入第二个参数:navigate('/Contact', { replace: true }); - 简单场景下也可直接传入字符串路径简化写法:
navigate('/Contact', { state: { text } });
内容的提问来源于stack exchange,提问作者Divya Shekhar
相关产品推荐
相关产品推荐

