遇到 TS 错误“React-router 的类型上不存在属性‘exact’”

Mik*_*e K 8 javascript typescript reactjs

我的应用程序无法编译,因为打字稿引发以下错误:

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<...>'
Run Code Online (Sandbox Code Playgroud)

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

我的依赖项:

"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",
}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,我从 master 签出到一个新分支并安装了@types/react-router,这引发了相同的错误,这就是为什么我确信错误来自这个包,但是运行npm uninstall @types/react-router并不能消除错误。让我的应用程序编译的唯一方法是签出到 master,否则问题仍然存在。

如果我安装最新的@types/react-router@3.0.22.

图像

这里发生了什么?

Muh*_*yar 6

如果你使用的是React Router v6,它不再支持exact。

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

// new - v6 <Route path="/" element={<MyComponent />} />
Run Code Online (Sandbox Code Playgroud)

正如他们的文档中所述:

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

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