为“匹配”连接 React Router 和 TypeScript

Connected React Router and TypeScript for `match`

Connected React Router 为 RouterState 导出类型,这太棒了!但是我没有看到 match 的类型。假设这些也可以导入并添加到减速器中,例如 RouterState 在下面和减速器中使用:

https://github.com/supasate/connected-react-router/blob/master/examples/typescript/src/reducers/index.ts#L13

const rootReducer = (history: History) => combineReducers({
  count: counterReducer,
  router: connectRouter(history)

})

export interface State {
  count: number
  router: RouterState
}

没有它,你就不能真正在连接的组件中使用 this.props.match 来匹配参数等。对于那些使用 TypeScript 并且还需要添加到 reducer 的人来说,这里是否有解决方法?还是我在这里遗漏了一个关键部分?非常感谢!

您有 2 种方法可以做到。

  1. 您可以在 mapStateToProps 中使用 createMatchSelector 函数从您的状态中提取 matchDEMO
import * as React from "react";
import { connect } from "react-redux";
import { createMatchSelector } from "connected-react-router";
import { match } from "react-router";
import { State } from "./reducers";

interface StateProps {
  match: match<{ name?: string }>;
}

const Hello = (props: StateProps) => (
  <div>Hello {props.match.params.name}!</div>
);

const mapStateToProps = (state: State) => {
  const matchSelector = createMatchSelector("/hello/:name");
  return {
    match: matchSelector(state)
  };
};

export default connect<StateProps>(
  mapStateToProps,
  null
)(Hello);
  1. 您可以直接从路由器获取 match,而不是从状态获取。 DEMO
import * as React from "react";
import { RouteComponentProps, withRouter } from "react-router";

const Hello = (props: RouteComponentProps<{ name?: string }>) => (
  <div>Hello {props.match.params.name}!</div>
);

export default withRouter(Hello);