繁体   English   中英

React Router v5 - 嵌套路由中的全局不匹配

[英]React Router v5 - Global No match in Nested Routes

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

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

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

应用程序.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} />

根据文档( 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>
  );
}

我认为这会很愚蠢 - 包含div应该在switch之外。 它现在按预期工作(我也改为使用component道具而不是子道具,但一旦 div 被移动,两者似乎都可以工作)。

工作代码:

<div className="loginForm align-middle">
    <img src="./img/logo.svg" alt="Restocker logo" className="w-100 p-3 mb-4"/>
    <Switch>
        <Route path="/verify" component={Verify}/>
        <Route path="/reVerify" component={ReVerify}/>
        <Route path="/register" component={Register}/>
        <Route path="/forgotPassword" component={ForgotPassword}/>
        <Route path="/resetPassword" component={() => Verify("password")}/>
        <Route path="/login" component={Login}/>
        <Route>
            <Redirect to="/login"/>
        </Route>
    </Switch>
</div>

请注意,现在Switch的所有直接子代现在都只是Route s

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM