这是我的代码
<Routes>
<Route path='/' element={<User/>} />
<Route path='/:userId/places' exact element={<UserPlaces/>} />
<Route path='/places/new' element={<NewPage/>}/>
<Route path='/places/:placeId' element={<UpdatePlace/>}></Route>
</Routes>
如果输入的不是这些网址,我想重定向到首页,但不支持使用最新版本的重定向方法。
最佳答案
Navigate
组件有效地取代了旧的 Redirect
成分。呈现一个“通配符”路由,该路由将重定向到您的主页路由。
例子:
<Route path="*" element={<Navigate to="/" replace />} />
相当于RRDv5的<Redirect from="*" to="/" />
代码:
import { Routes, Route, Navigate } from 'react-router-dom';
...
<Routes>
<Route path='/' element={<User />} />
<Route path='/:userId/places' element={<UserPlaces />} />
<Route path='/places/new' element={<NewPage />} />
<Route path='/places/:placeId' element={<UpdatePlace />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
关于reactjs - 如果url无效如何重定向到主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73678425/