use*_*886 65 reactjs react-router
我刚刚将react-router-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>
)
}
Run Code Online (Sandbox Code Playgroud)
因此,除了未找到的页面之外,一切都按预期工作(包括主页),即使添加path="/*"
或添加也无法工作path="*"
有什么简单的解决方案吗?
Hai*_*373 100
<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>
Run Code Online (Sandbox Code Playgroud)
小智 29
React Router v6 不使用精确属性来匹配精确路由。默认情况下它匹配确切的路由。要匹配任何值,请在路由路径中使用“*”。
<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
Run Code Online (Sandbox Code Playgroud)
小智 11
React router v6 没有 Switch 所以你需要声明 path='*'
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact/>} />
<Route path="*" element={<NotFound/>} />
</Routes>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)
gre*_*tte 11
您可以使用
<Route path="*" element={ <Navigate to="/404" replace />} />
Run Code Online (Sandbox Code Playgroud)
这样你就可以进行重定向和网址替换
例如 :
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
Run Code Online (Sandbox Code Playgroud)
您需要渲染路径为 的 Route *
,React Router 将确保仅在其他 Route 都不匹配时才渲染它。
如果您的 404 组件名称是PageNotFound
:
<路线路径=“*”元素={<PageNotFound/>} />
1 Stackblitz链接(其实现有点不同)
归档时间: |
|
查看次数: |
63384 次 |
最近记录: |