Estoy usando react-router v6 y tengo un componente de aplicación tan simple.
type RouteType = { path: string; element: any; } function App() { const [user] = useAuthState(auth); const USER_ROUTES: RouteType[] = user ? [ { path: '/signin', element: <Login /> }, { path: '/signup', element: <Signup /> }, ] : [ { path: '/games', element: <Games /> }, { path: '/tournaments', element: <Tournaments /> }, { path: '/mymatches', element: <MyMatches /> }, ]; const PUBLIC_ROUTES: RouteType[] = [ { path: '*', element: <NotFound /> }, { path: '/', element: <Home /> }, ]; return ( <> <Header /> <Routes> {[...USER_ROUTES, ...PUBLIC_ROUTES].map( ({ path, element }, i) => <Route key={i} path={path} element={element} />, )} </Routes> </> ); } Pero independientemente del valor del user , siempre muestra * ruta (NotFound). ¿Cómo puedo reescribir este fragmento de código con tal concepto pero sin error?
Gracias.
Por lo que puedo ver, ha invertido la lógica para sus rutas de usuario. Cuando user es sincero, representa las rutas de inicio de sesión/registro en lugar de las rutas a las que un usuario "autenticado" debería poder acceder.
Cuando user es falsey "/games" , "/tournaments" y "/mymatches" se devuelven para las rutas de usuario. Si intenta navegar a "/signin" iniciar sesión", la ruta "*" lo detecta y representa el componente NotFound , ya que actualmente no se representa ninguna ruta para "/signin" iniciar sesión".
Cambie las rutas devueltas por USER_ROUTES cuando user sea veraz.
function App() { const [user] = useAuthState(auth); const USER_ROUTES: RouteType[] = user ? [ // truthy user, render user routes { path: '/games', element: <Games /> }, { path: '/tournaments', element: <Tournaments /> }, { path: '/mymatches', element: <MyMatches /> }, ] : [ // falsey user, render signin/signup routes to authenticate { path: '/signin', element: <Login /> }, { path: '/signup', element: <Signup /> }, ]; const PUBLIC_ROUTES: RouteType[] = [ { path: '*', element: <NotFound /> }, { path: '/', element: <Home /> }, ]; return ( <> <Header /> <Routes> {[...USER_ROUTES, ...PUBLIC_ROUTES].map(({ path, element }) => ( <Route key={path} path={path} element={element} /> ))} </Routes> </> ); }