使用 TypeScript 的 react-router-dom

新手上路,请多包涵

我正在尝试将反应路由器与 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);

原文由 Haris Bašić 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 536
1 个回答

我使用不同的方法来解决这个问题。我总是将不同的属性(路由器、常规和分派)分开,因此我为我的组件定义了以下接口:

 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 接口的参数。

原文由 Ramon de Klein 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进