我正在使用反应路由器和打字稿从路由中获取id变量以在组件中使用,打字稿抱怨:
类型"{}"缺少类型中的以下属性 'match': params, isExact, path, url
这是我的代码(App.tsx(:
<Route path='/posts/:id'>
<Post />
</Route>
邮政.tsx :
import React from 'react';
import { match } from 'react-router';
interface Identifiable {
id: string
params: string,
isExact: string,
path: string,
url: string,
}
const Post = (mathedRoute: match<Identifiable>) => {
return <h1>{mathedRoute.params.id}</h1>
}
export default Post;
提前感谢您的帮助。
为了提取匹配项,您需要呈现组件,而不是将其作为子项传递。
<Route path='/posts/:id' render={({match}) => <Post match={match} />} />
Typescript 可能仍然会抱怨它,在这种情况下,您需要从"react-router-dom"导入 RouteComponentProps 并可能扩展它。
然而!好消息是,反应路由器钩子存在!
我建议使用它们,尤其是useRouteMatch和useParams钩子。
您可以使用标准方式:
import React from 'react';
import { Route, RouteComponentProps, Switch } from 'react-router-dom';
interface PostParams {
id: string;
}
function Post(props: RouteComponentProps<PostParams>) {
return <>{props.match.params.id}</>;
}
export function App() {
return (
<Switch>
<Route path='/posts/:id' component={Post}/>
</Switch>
);
}
或钩子方式:
import React from 'react';
import { Route, Switch, useParams } from 'react-router-dom';
interface PostParams {
id: string;
}
function Post() {
const { id } = useParams<PostParams>();
return <>{id}</>;
}
export function App() {
return (
<Switch>
<Route path='/posts/:id'>
<Post/>
</Route>
</Switch>
);
}
在你的代码中,你试图将它们混合在一起.
reed 更多关于 react router v5