Fuz*_*ree 4 javascript typescript react-router react-router-dom
我正在尝试使用matchPath从父容器中提取路由参数,如/sf/answers/3184474891/ 中所述
const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });
Run Code Online (Sandbox Code Playgroud)
当 I 时console.log(topicMatch.params),该对象topic设置了密钥,但如果我尝试访问,则会topicMatch.params.topic出现以下错误:
错误 TS2339:类型“{}”上不存在属性“topic”。
const RouterApp = withRouter<{}>(
class App extends React.Component<RouteComponentProps<{}>, AuthState> {
render() {
const { history } = this.props;
const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });
if (topicMatch) {
console.log(topicMatch.params); // has topic key
console.log(topicMatch.params.topic); // causes compile error
}
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<h2>Welcome to React</h2>
</div>
</div>
);
}
}
);
Run Code Online (Sandbox Code Playgroud)
matchPath是一个参数化函数,它采用泛型类型<P>并返回与match<P>. 由您来定义P;否则我实际上不确定 TypeScript 如何确定返回类型。
matchPath<{topic: "string"}>(...)
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您也可以创建自己的类型,例如
interface RouteParams {
topic: string;
}
Run Code Online (Sandbox Code Playgroud)
然后做matchPath<RouteParams>(...)。
| 归档时间: |
|
| 查看次数: |
1135 次 |
| 最近记录: |