首页 > 解决方案 > 如何从Route获取路径?

问题描述

我一直在尝试捕获一个未定义的 URL 并将其传递给我的组件来处理它(显示消息)。我不确定如何传递已捕获的当前 URL。谢谢你。

<Switch>
    <Route exact path='*' render={() => <HttpError data={"Undefined URL: " + this.props.match}/>}/>
</Switch>

标签: reactjsreact-routerreact-router-dom

解决方案


将路由道具传递给正在渲染的组件。访问props.match.url以获取正在呈现的路由的 URL。

<Switch>
  <Route
    exact
    path='*'
    render={(routeProps) => (
      <HttpError data={"Undefined URL: " + routeProps.match.url} />
    )}
  />
</Switch>

如果您将其用作一种“404”路线,那么您可以将其放在您Switch的最后一个,删除exact道具(您也可以删除path道具),如果在匹配之前没有任何内容,那么这将由Switch.

<Switch>
  // ... all other routes
  <Route
    render={(routeProps) => (
      <HttpError data={"Undefined URL: " + routeProps.match.url} />
    )}
  />
</Switch>

推荐阅读