react-router-dom v6 useRoutes条件使用受保护路由时路由匹配报错求助
问题原因
问题出在protectedRoutes的子路由使用了绝对路径,导致这些子路由无法被正确识别为父路由/的嵌套路由。当登录后路由数组切换为protectedRoutes时,用户访问的私有路径(如/profile)无法在路由数组中找到匹配项,从而触发"No routes matched location"错误。
解决方案
1. 修正嵌套路由路径格式
将protectedRoutes中子路由的path改为相对路径(去掉开头的/),让它们正确关联到父路由/下:
//protected.js import { Navigate, Outlet } from 'react-router-dom'; import { Profile } from '@/features/users'; import { Dashboard } from '@/features/misc'; const App = () => { return ( <div> <h1>Protected Routes View</h1> <Outlet /> </div> ); }; export const protectedRoutes = [ { path: '/', element: <App />, children: [ { path: 'profile', element: <Profile /> }, // 改为相对路径 { path: 'dash', element: <Dashboard /> }, // 改为相对路径 { path: '*', element: <Navigate to="." /> }, // 通配符用相对路径,匹配/* ], }, ];
2. 补全公共路由的通配符匹配
为避免未登录时访问私有路径报错,在publicRoutes中添加通配符路由,将未知路径重定向到登录页:
//public.js import { Login } from "@/features/auth/routes/Login"; import { Register } from "@/features/auth/routes/Register"; import { Navigate } from 'react-router-dom'; export const publicRoutes = [ { path: '/auth/login', element: <Login />, }, { path: '/auth/register', element: <Register />, }, { path: '*', element: <Navigate to="/auth/login" /> }, // 添加未知路径重定向 ];
3. 处理auth状态加载过渡
如果useAuth存在状态加载延迟,在状态未确定时显示加载组件,避免路由切换瞬间的匹配错误:
///index.js import { useRoutes } from 'react-router-dom'; import { protectedRoutes } from './protected'; import { publicRoutes } from './public'; import { useAuth } from '@/lib/auth'; export const AppRoutes = () => { const auth = useAuth() // 等待auth状态加载完成再渲染路由 if (auth.loading) { return <div>Loading...</div>; } const routes = auth.user ? protectedRoutes : publicRoutes; const element = useRoutes([...routes]) return <> {element} </>; };
内容的提问来源于stack exchange,提问作者yak-198
相关产品推荐
相关产品推荐

