reactjs - 如何在 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 页面。
请帮我。
谢谢。
解决方案
您必须为 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>
);
}
推荐阅读
- python - Python3中的自动舍入
- c# - 关闭时如何在通知点击中打开应用程序
- c - 如何在c中使用指针合并排序字符串数组?
- tpu - 模拟/模拟 Google TPU 进行开发和调试
- javascript - React Native for Web:我的组件在状态更新时不会重新渲染
- c++ - C++ ATL | _InternalQueryInterface 标识符未找到
- typescript - 如何将“then”回调函数的结果返回到 loopback 4 控制器
- javascript - MutationObserver 的 `observe` 函数不执行回调函数
- python - 类型错误:__init__() 缺少 1 个必需的位置参数:'kernel_size'
- docker - 如何将卷的数据传输到 docker 本地主机上的另一个卷?