React TypeScript:动态路径的正确类型

React TypeScript: Correct type for dynamic path

路由器看起来像这样

import { BrowserRouter, Route, Switch } from 'react-router-dom';

...
<Route exact path='/confirm-email/:confirmationCode' component={ConfirmEmail} />
                                        ^
//                                      This is the value that gets passed to the props

加载的组件是

import { RouteComponentProps } from 'react-router-dom';

interface PropsInterface extends RouteComponentProps<{}> {
  confirmationCode: string;
}
const ConfirmEmail: React.FC<PropsInterface>  = (props: PropsInterface) => {
  const confirmationCode = props.match.params.confirmationCode;
                                                   ^
//                                                 Error Here!

我得到的错误是Property 'confirmationCode' does not exist on type '{}'.ts(2339)

这不是 react-router-dom with TypeScript 的副本,因为它没有解决作为 prop

传递的动态路径

:confirmationCode 是 Route 道具的一部分,props.match.params.confirmationCode

所以属于 RouteComponentProps

的道具

因此您需要将其传递给 RouteComponentProps,例如:

import { RouteComponentProps } from 'react-router-dom';
interface PropsInterface extends RouteComponentProps<{confirmationCode: string}> {
 others:any; // Other props that belong to component it self not Router
}

如果你想销毁更多的路由参数,或者更清楚

   interface IParams { confirmationCode:string; ....  }
   interface IProps extends RouteComponentProps<IParams>{....}

所以您看到这与重复问题中涵盖的内容完全相同吗?区别在于命名。