你有两种方法可以做到这一点。
- 您可以使用
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);
- 您可以
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);