【问题标题】:React Router v5 - Global No match in Nested RoutesReact Router v5 - 嵌套路由中的全局不匹配
【发布时间】:2021-03-22 10:02:04
【问题描述】:

我的 React 应用中有两个路由“堆栈”:

  • 公开(登录、注册、404 等 - /login、/register)
  • 私人(仪表板 - /app/*)

当用户登录时,仪表板路由堆栈用于下一个嵌套路由器匹配子页面的位置。 当路由不存在时,我想显示来自“公共”堆栈的全局无匹配 (404) 路由,但是当我在路由器末尾有此路由时,会显示空仪表板路由,而不是设置中的最后一个路由:

App.tsx

return (
      <Router>
        <Switch>
          <Route path="/login" component={Login} exact />
          <Route path="/app/*" render={(props) => (isAuthenticated ? <Dashboard {...props} /> : <Redirect to="/login" />)} />
          <Route component={NotFound} />
        </Switch>
      </Router>
    );

仪表板.tsx

export default function Dashboard(props: RouteComponentProps): ReactElement {
  return (
    <div>
      <div>Dashboard</div>
      <Switch>
        <Route path="/" component={Welcome} exact />
        <Route path="/create" component={CreateContent} />
        <Route path="/manage" component={ManageContent} />
      </Switch>
    </div>
  );
}

因此,例如当我访问 /foobar 时,我看到组件 Dashboard 的内容没有任何其他内容。

我试图在仪表板的末尾进行重定向,但这在我看来并不是设计好的:


// End of Dashboard Switch
<Route render={() => <Redirect to="/404" />} />

// Changed NotFound route
<Route path="/404" component={NotFound} />

【问题讨论】:

    标签: javascript reactjs typescript react-router


    【解决方案1】:

    根据文档 (https://reactrouter.com/web/guides/primary-components/route-matchers):

    当 a 被渲染时,它会搜索其子元素以找到其路径与当前 URL 匹配的元素。当它找到一个时,它会渲染它并忽略所有其他的。

    使用重定向块有助于解决这种情况下的问题。将其添加到您的仪表板组件中:

    export default function Dashboard(props: RouteComponentProps): ReactElement {
      return (
        <div>
          <div>Dashboard</div>
          <Switch>
            <Route path="/" component={Welcome} exact />
            <Route path="/create" component={CreateContent} />
            <Route path="/manage" component={ManageContent} />
            <Route><Redirect to="/404" /></Route>
          </Switch>
        </div>
      );
    }
    

    【讨论】:

    猜你喜欢
    • 2017-09-03
    • 2021-04-23
    • 1970-01-01
    • 2020-10-10
    • 2021-03-02
    • 2020-06-05
    • 2021-12-09
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多