0

我试图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,它不会通过打字稿类型检查。
除了用于&合并所有类型之外还有什么建议吗?
提前致谢!

4

1 回答 1

0

您的 OwnProps 定义错误。它需要是:

interface OwnProps extends RouteComponentProps<MatchProps> {

}

因为 React-router Route 组件将他的 props 直接推送到你的 props 对象,所以它没有包裹在 routeProps 属性上。

这也应该通过 TypeScript 检查:)

于 2020-01-31T07:57:13.433 回答