React Router <Navigate> 非预期跳转:访问子路由仍被重定向
问题原因及解决方案
你的问题出在父路由movies的element中直接放置了<Navigate>组件——只要进入/movies下的任何子路由(包括/movies/popular),父组件都会渲染并执行这个重定向,导致所有子路由都被跳转到/movies/trending。
修复方案一:用Index路由实现根路径重定向
把重定向逻辑放到index路由中,只有当访问/movies(无子路径)时才触发重定向:
<Route path="movies"> {/* 仅访问/movies时重定向到trending */} <Route index element={<Navigate to="trending" replace />} /> <Route path="trending" element={<MoviesTrending />} /> <Route path="top_rated" element={<MoviesTopRated />} /> <Route path="popular" element={<MoviesPopular />} /> </Route>
修复方案二:带公共布局的条件重定向
如果父路由需要渲染公共内容(比如电影分类导航栏),可以通过useLocation判断当前路径,仅在严格匹配/movies时才重定向:
import { Navigate, Outlet, useLocation } from 'react-router-dom'; function MoviesLayout() { const location = useLocation(); // 仅当路径为/movies时执行重定向 if (location.pathname === '/movies') { return <Navigate to="trending" replace />; } return ( <div> {/* 这里可以添加公共布局元素,比如导航栏 */} <Outlet /> </div> ); } // 路由配置 <Route path="movies" element={<MoviesLayout />}> <Route path="trending" element={<MoviesTrending />} /> <Route path="top_rated" element={<MoviesTopRated />} /> <Route path="popular" element={<MoviesPopular />} /> </Route>
这两种方式都能保证:访问/movies时自动跳转到/movies/trending,而访问/movies/popular等子路由时正常渲染对应组件。
内容的提问来源于stack exchange,提问作者SHUVAM JASWAL
相关产品推荐
相关产品推荐

