首页 > 解决方案 > 如何在 React 路由器中使用具有 404 页面的多个布局

问题描述

我在反应路由中遇到多个布局问题并且找不到页面

主要路线 => 主要布局

管理员溃败 => 带有管理员布局

登录页面 => 没有任何布局

404 页面 => 没有任何布局

我的代码:

import React from 'react';
import { BrowserRouter as Router, Redirect, Route, Switch } from 'react-router-dom';
import AuthContextProvider from './context/authContext/AuthContext';
const main = () => {
  return (
    <div>
      <Navbar />
      <Switch>
        <Route path="/" exact component={Main} />
        <Route path="/contact" exact component={Contact} />
        <Route path="/about" exact component={About} />
        <Route path="/blog" exact component={Blog} />
      </Switch>
    </div>
  )
}
const admin = () => {
  return (
    <div>
      <PanelNavbar />
      <Switch>
        <Route path="/admin/panel" exact component={Panel} />
        <Route path="/admin/panel/menu" exact component={Menu} />
        <Route path="/admin/panel/blog" exact component={Blog} />
      </Switch>
    </div>
  )
}
const App = (props) => {
  return (
    <Router>
      <AuthContextProvider>
        <Switch>
          <Route path="/admin/login" exact component={Login} />
          <Route path='/admin' component={admin} />
          <Route path="/" component={main} />
          <Route path='/404' component={Page404} />
          <Redirect to='/404' />
        </Switch>
      </AuthContextProvider>
    </Router>
  );
}

我不希望 404 页面采用任何布局。

我只想将错误的地址重定向到 404 页面。

请帮我。

谢谢。

标签: reactjsreact-routerreact-router-dom

解决方案


您必须为 404 页面定义路由,如下例所示:

<Route path='/404' component={Page404} />
<Redirect from='*' to='/404' />

然后如果 URL 与定义的路由不匹配,用户将被重定向到 404 页面/路由。

以及关于没有任何邻居布局的 404 页面......应该在最低层并且没有我的 UI 组件邻居,例如:

function AppRoute({...params}) {
    return (
    <>
        <AnyComponentLikeNavBar />
        <Route {...params} />
    </>
    );
}

function App() {
    return (
    <BrowserRouter>
        <Switch>
            <AppRoute path="/" exact component={Main} />
            <AppRoute path="/contact" exact component={Contact} />
            <AppRoute path="/about" exact component={About} />
            <AppRoute path="/blog" exact component={Blog} />

            <Route path='/404' component={Page404} />
            <Redirect from='*' to='/404' />
        </Switch>
    </BrowserRouter>
    );
}

推荐阅读