我试图collection从 url 抓取,所以我在下面写了代码
// parent
<Route
path={`${this.props.match.path}/:collection`}
component={Collection}
/>
//child
interface MatchProps {
collection: string;
}
interface OwnProps {
routeProps: RouteComponentProps<MatchProps>;
}
const mapStateToProps = (
state: StoreState,
ownProps: OwnProps
): StateToProps => {
console.log(ownProps);
return {
collection: selectCollection(ownProps.routeProps.match.params.collection)(state)
};
};
这会引发错误 that Cannot read property 'match' of undefined,但是如果我更改ownPropsto的类型RouteComponentProps<MatchProps>并更改相应的 return 语句,则代码将起作用。
两次,控制台都输出完全相同的匹配结果
match:
path: "/shop/:collection"
url: "/shop/hats"
isExact: true
params: {collection: "hats"}
经过挖掘并发现 connect 会将所有道具合并到最终设置的道具中。
但是如果我只是编码ownProps.match而不是ownProps.routeProps.match,它不会通过打字稿类型检查。
除了用于&合并所有类型之外还有什么建议吗?
提前致谢!