已连接的React Router导出RouterState
的类型,这很棒!但是,我看不到match
的输入。假设那些也可以导入并添加到减速器中,例如RouterState
在下面以及在减速器中使用:
const rootReducer = (history: History) => combineReducers({
count: counterReducer,
router: connectRouter(history)
})
export interface State {
count: number
router: RouterState
}
没有这些,您不能真正在连接的组件中使用this.props.match
来匹配参数等。对于使用TypeScript并需要添加到reducer的用户来说,这里是否有解决方法?还是我在这里缺少关键部分?非常感谢!
答案 0 :(得分:0)
您有2种方法。
createMatchSelector
中的mapStateToProps
函数从您的状态中提取match
。 DEMO 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
。 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);