连接的React路由器和“匹配”的打字稿



连接的react路由器导出了RouterState的类型,这很棒!但是,我看不到match的键入。会假设这些这些也可以被导入并添加到还原器中,例如RouterState在下面和还原器中使用:

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

const rootReducer = (history: History) => combineReducers({
  count: counterReducer,
  router: connectRouter(history)
})
export interface State {
  count: number
  router: RouterState
}

没有哪个,您将无法真正在连接的组件中使用 this.props.match,以匹配参数等。这里的人是否有使用Typescript的人也需要添加到还原器?还是我在这里错过关键部分?非常感谢!

您有2种方法。

  1. 您可以在mapStateToProps中使用createMatchSelector功能从您的州提取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);

相关内容

  • 没有找到相关文章

最新更新