连接React Router和TypeScript以进行匹配

时间:2019-05-01 18:30:21

标签: reactjs typescript react-router connected-react-router

已连接的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的用户来说,这里是否有解决方法?还是我在这里缺少关键部分?非常感谢!

1 个答案:

答案 0 :(得分:0)

您有2种方法。

  1. 您可以使用createMatchSelector中的mapStateToProps函数从您的状态中提取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. 您可以直接从路由器而不是从州获得matchDEMO
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);