You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复React Router中「Property 'push' does not exist on type 'NavigateFunction'」错误?

React Router DOM中NavigateFunction无push方法的错误解决

错误原因

你遇到的问题是因为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 05:14:58