我刚刚升级到反应路由器dom的v6beta,因为我想组织我的路由,但404页面现在坏了:
export function AllRoutes(props) {
return(
<Routes>
<Route path="/about-us">
<Route path="contact"> <AboutContact/> </Route>
<Route path="our-logo"> <AboutLogo/> </Route>
<Route path="the-mission"> <AboutMission/> </Route>
<Route path="the-team"> <AboutTeam/> </Route>
<Route path="our-work"> <AboutWork/> </Route>
</Route>
<Route path="/user">
<Route path="sign-in"> <UserSignIn/> </Route>
<Route path="sign-up"> <UserSignUp/> </Route>
</Route>
<Route path="/">
<Home/>
</Route>
<Route >
<NotFound/>
</Route>
</Routes>
)
}
因此,除了未找到的页面外,所有内容都按预期工作(包括主页(,即使添加path="/*"
或path="*"
,也无法工作
有什么简单的解决方案吗?
<Routes>
// Use it in this way, and it should work:
<Route path='*' element={<NotFound />} />
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/settings" element={<Settings />} />
</Routes>
<BrowserRouter>
<div className="App">
<Header />
</div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/profile" element={<Profile />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter> enter code here
react路由器v6没有交换机因此您需要声明path='*'
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact/>} />
<Route path="*" element={<NotFound/>} />
</Routes>
</BrowserRouter>
您可以使用
<Route path="*" element={ <Navigate to="/404" replace />} />
这样你就有了重定向和url替换
例如:
import React from 'react'
import { BrowserRouter as Router, Routes , Route, Navigate } from 'react-router-dom'
import Home from '../../pages/Home'
import Account from '../../pages/Account'
import Contact from '../../pages/Contact'
import NotFound from '../../pages/NotFound'
const AllRoutes= () => {
return(
<Router>
<Routes>
<Route path="/" element={ <Home /> } />
<Route path="/Account" element={ <Account /> } />
<Route path="/Contact" element={ <Contact /> } />
<Route path="/404" element={ <NotFound /> } />
<Route path="*" element={ <Navigate to="/404" replace />} />
</Routes>
</Router>
)
}
export default AllRoutes
您需要渲染路径为*
的Route,React Router将确保仅在其他Routes都不匹配的情况下渲染它。
如果您的404组件名称为PageNotFound
:
<路由路径="*"element={<PageNotFound/>}/>
1 Stacklitz链接(其实现有点不同(
2最简单的例子是
创建组件并在组件内部创建函数NotFound。
在app.js中,create and give path="*"元素应该是NotFound函数。