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

React Router Dom Link组件在React TypeScript中的类型错误问题

React Router v6 Link组件state类型错误的解决办法

你的代码

<Link 
  style={{textDecoration: 'none'}} 
  to={{            
    state: { fromDashboard: true },            
    pathname:`/Forum/thread/${thread.threadLink}`,          
  }} 
>            
  {thread.title}
</Link>

报错信息

Type '{ state: { fromDashboard: true; }; pathname: string; }' is not assignable to type 'To'.
Object literal may only specify known properties, and 'state' does not exist in type 'Partial'.ts(2322)
index.d.ts(70, 5): The expected type comes from property 'to' which is declared here on type 'IntrinsicAttributes & LinkProps & RefAttributes'

依赖版本

  • react: ^18.2.0
  • react-dom: ^18.2.0
  • react-router-dom: ^6.8.0

核心解决方案

React Router v6 彻底改变了state的传递方式——state不再是to对象的属性,而是作为Link组件的独立props单独传入。修改后的代码如下:

<Link 
  style={{textDecoration: 'none'}} 
  to={`/Forum/thread/${thread.threadLink}`}
  state={{ fromDashboard: true }}
>            
  {thread.title}
</Link>

如果需要使用包含search、hash等属性的对象形式to,同样把state抽出来:

<Link 
  style={{textDecoration: 'none'}} 
  to={{
    pathname: `/Forum/thread/${thread.threadLink}`,
    // 这里可以加search、hash等属性,但不要放state
  }}
  state={{ fromDashboard: true }}
>            
  {thread.title}
</Link>

额外排查建议

  1. React Router v6 内置了完整的类型定义,不需要单独安装@types/react-router或@types/react-router-dom,你之前卸载这些包的操作是对的,不用重新装。
  2. 如果修改后还是报错,建议清理依赖缓存后重装:
    rm -rf node_modules package-lock.json
    npm install
    

内容的提问来源于stack exchange,提问作者Neo Chen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:17:32