我正在尝试将react路由器与TypeScript一起使用。但是,我在使用withRouter函数时遇到了一些问题。在最后一行,我得到了一个非常奇怪的错误:
Argument of type 'ComponentClass<{}>' is not assignable to parameter of type 'StatelessComponent<RouteComponentProps<any>> | ComponentClass<RouteComponentProps<any>>'.
Type 'ComponentClass<{}>' is not assignable to type 'ComponentClass<RouteComponentProps<any>>'.
Type '{}' is not assignable to type 'RouteComponentProps<any>'.
Property 'match' is missing in type '{}’代码看起来像这样:
import * as React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router-dom';
interface HomeProps extends RouteComponentProps<any> {
}
interface HomeState { }
class Home extends React.Component<HomeProps, HomeState> {
constructor(props: HomeProps) {
super(props);
}
public render(): JSX.Element {
return (<span>Home</span>);
}
}
const connectModule = connect(
(state) => ({
// Map state to props
}),
{
// Map dispatch to props
})(Home);
export default withRouter(connectModule);发布于 2017-10-24 05:44:09
我使用了一种不同的方法来解决这个问题。我总是将不同的属性(路由器、常规和分派)分开,因此我为我的组件定义了以下接口:
interface HomeRouterProps {
title: string; // This one is coming from the router
}
interface HomeProps extends RouteComponentProps<HomeRouterProps> {
// Add your regular properties here
}
interface HomeDispatchProps {
// Add your dispatcher properties here
}您现在可以创建一个新类型,将所有属性组合到一个类型中,但我总是在组件定义期间组合这些类型(我不在这里添加状态,但如果需要的话,请继续)。组件定义如下所示:
class Home extends React.Component<HomeProps & HomeDispatchProps> {
constructor(props: HomeProps & HomeDispatchProps) {
super(props);
}
public render() {
return (<span>{this.props.match.params.title}</span>);
}
}现在我们需要通过容器将组件连接到状态。它看起来是这样的:
function mapStateToProps(state, ownProps: HomeProps): HomeProps => {
// Map state to props (add the properties after the spread)
return { ...ownProps };
}
function mapDispatchToProps(dispatch): HomeDispatchProps {
// Map dispatch to props
return {};
}
export default connect(mapStateToProps, mapDispatchToProps)(Hello);此方法允许完全类型化的连接,因此组件和容器是完全类型化的,因此可以安全地重构它。对于重构来说,惟一不安全的是映射到HomeRouterProps接口的路由中的参数。
发布于 2017-06-15 23:43:55
我认为这是一个typescript typings编译问题,但我找到了一个解决方法:
interface HomeProps extends RouteComponentProps<any>, React.Props<any> {
}发布于 2017-06-13 10:20:28
看起来您有正确的用法可以将匹配、历史和位置属性应用到您的组件。我会检查一下您的node_modules目录,看看您有哪些版本的react-router和react-router-dom,以及@types模块。
我的代码与您的基本相同,并且我的代码适用于以下版本:
{
"@types/react-router-dom": "^4.0.4",
"react-router-dom": "^4.1.1",
}https://stackoverflow.com/questions/44118060
复制相似问题