4

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 的人来说,这里有解决方法吗?或者我在这里错过了一个关键部分?非常感谢!

4

1 回答 1

8

你有两种方法可以做到这一点。

  1. 您可以使用createMatchSelector内部函数从您的状态mapStateToProps中提取。演示match
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直接从路由器获取,而不是从状态获取。演示
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);
于 2019-05-04T07:16:02.347 回答