为什么带有子组件的路由会导致类型错误,而带有组件的路由不会?

Why does Route with children as components cause Typeerror, but route with component does not?

我正在使用“react-router-dom”:“5.2.0”。根据此 post and blog 将道具从路由传递到组件,我需要做的就是像这样简单地传递它:

{caseManagement && <Route path={`${SPA_PREFIX}/cases/:caseToken`}> <CaseView sarReport={sarReport} /> </Route>}

然而,当我这样做时,我的编译器没有抱怨,但在我的浏览器中我收到以下错误。

CaseView.jsx:48 Uncaught TypeError: Cannot read properties of undefined (reading 'params') at CaseView (CaseView.jsx:48:1)

如果我将代码更改为以下代码,它将按预期工作。

{caseManagement && <Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />}

当然在这个实现中我没有传递任何道具给它。如何将道具传递给我的组件? 下面是我传递道具的组件的相关代码

const CaseView = ({
  match: { params: { caseToken } },
}, sarReport ) => {
...

问题

  • <Route path={`${SPA_PREFIX}/cases/:caseToken`}>
      <CaseView sarReport={sarReport} />
    </Route>
    

    CaseView 渲染为 child 时,您可以传递任何您喜欢的道具,但路线道具,特别是 match 是not通过,访问props.match.params.

    时出现错误
  • <Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />
    

    component 道具上渲染时,路线道具 传递的,因此 props.match.params 有效, 但现在你不能通过额外的 sarReport prop.

解决方案

react-router-dom v5 中传递 route props (i.e. history, location, and match) and other custom props you should use the render function prop.

示例:

<Route
  path={`${SPA_PREFIX}/cases/:caseToken`}
  render={routeProps => <CaseView {...routeProps} sarReport={sarReport} />}
/>

有关渲染路由组件的不同方法之间的更多详细信息和解释,请参阅 Route render methods