【问题标题】:Running into TS error "Property 'exact' does not exist on type' with react-router"遇到 TS 错误“使用 react-router 的类型'不存在属性'exact'”
【发布时间】:2020-07-25 23:29:15
【问题描述】:

我的应用程序无法编译,因为 typescript 抛出以下错误:

Type '{ path: string; exact: true; render: () => Element; }' is not assignable to type 'IntrinsicAttributes
 & IntrinsicClassAttributes<Component<RouteProps, any, any>> & Readonly<RouteProps> & Readonly<...>'.
  Property 'exact' does not exist on type 'IntrinsicAttributes
  & IntrinsicClassAttributes<Component<RouteProps, any, any>> & Readonly<RouteProps> & Readonly<...>'

我不确定发生了什么,但我相当肯定这个问题是在我按照 Github 上的 suggestion 安装 @types/react-router@3.0.2 后出现的,但我不确定为什么。

我的依赖:

"dependencies": {
  "@types/react-dom": "^16.9.4",
  "@types/react-router": "^3.0.2",
  "@types/react-router-dom": "^5.1.3",
  "connected-react-router": "^6.7.0",
  "react-dom": "^16.12.0",
  "react-router": "^5.1.2",
  "react-router-dom": "^5.1.2",
}

奇怪的是,我将 master 签出到一个新的分支并安装了 @types/react-router,这引发了同样的错误,这就是为什么我确定错误来自这个包,但是运行 npm uninstall @types/react-router 没有t摆脱错误。让我的应用程序编译的唯一方法是检出到 master,否则问题仍然存在。

如果我安装最新的@types/react-router@3.0.22,问题仍然存在。

这是怎么回事?

【问题讨论】:

  • 尝试将所有内容更新到最新版本:npx npm-check-update -u(这将重写您的package.json。此外,删除 node_modules 和 package-lock.json 并重新安装包。

标签: javascript reactjs typescript


【解决方案1】:

如果你使用 react router v6,它不再支持exact了。

// old - v5 <Route exact path="/" component={MyComponent} />

// new - v6 <Route path="/" element={<MyComponent />} />

如他们的文档中所述:

您不再需要使用精确的道具了。这 是因为默认情况下所有路径都完全匹配。

您可以参考这个迁移指南:here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2020-05-08
    • 2019-03-06
    • 2018-11-30
    • 2022-01-21
    • 2021-05-10
    相关资源
    最近更新 更多