首页 > 解决方案 > react router dom v5中的嵌套路由和未找到路由

问题描述

在尝试在反应路由器 dom v5 中创建嵌套路由时,我发现这个答案解释了如何很好地做到这一点

(请看这里的代码,因为它与上面提到的答案有点不同)

布局.js

const NotFound = () => <h1>Not Found</h1>;

function Layouts() {
  return (
    <Switch>
      <Route path="/auth" component={AuthLayout} />
      <Route path="/app" component={AppLayout} />
      <Route path="/" component={NotFound} />
    </Switch>
  );
}

授权布局

const Signup = () => <p>Login</p>;
const Login = () => <p>Sign up</p>;

function AuthLayout() {
  return (
    <div>
      <h1>Auth Layout</h1>
      <Route path="/auth/signup" exact component={Signup} />
      <Route path="/auth/login" exact component={Login} />
      {/* Commenting this because I want to go to NotFound component */}
      {/* <Redirect from="/auth" to="/auth/login" exact /> */}
    </div>
  );
}

应用布局

const Home = () => <p>Home</p>;
const Dashboard = () => <p>Dashboard</p>;

function AppLayout() {
  return (
    <div>
      <h1>App Layout</h1>
      <Route path="/app/home" exact component={Home} />
      <Route path="/app/dashboard" exact component={Dashboard} />
      {/* Commenting this because I want to go to NotFound component */}
      {/* Redirect from="/app" to="/app/home" exact /> */}
    </div>
  );
}

但这有一个问题,如果你去一个路线,/app/somethingnotfound它不会去<Route path="/" component={NotFound} />,它会“留在里面”AppLayout并且不渲染任何路线。

在这种情况下我该怎么做/app/somethingnotfound<Route path="/" component={NotFound} />

编辑:

更清楚一点:我不想只是在<Route component={NotFound} />里面添加AuthLayoutAppLayout因为它会渲染其他东西。我真正需要的是展示顶级水平NotFound

标签: reactjsreact-routerreact-router-domreact-router-v5

解决方案


未找到的组件通常是这样工作的:

<Router>
  <Switch>
    <Route exact path="/auth" component={AuthLayout} />
    <Route exact path="/app" component={AppLayout} />
    <Route component={NotFound} />
  </Switch>
</Router>

但是你不能标记/authand/app因为exact它们包含嵌套路由。所以,你应该这样做:

<Router>
  <Switch>
    <Route path="/auth" component={AuthLayout} />
    <Route path="/app" component={AppLayout} />
    <Route exact path="/404" component={NotFound} />
    <Redirect to='/404' />
  </Switch>
</Router>

AppLayout以及带有嵌套路由的组件(例如):

<>
<h1>App Layout</h1>
<Switch>
  <Route path="/app/home" exact component={Home} />
  <Route path="/app/dashboard" exact component={Dashboard} />
  <Redirect to="/404" />
</Switch>
</>

推荐阅读