Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
Ruta de autenticación de React PrivateRoute

Estoy trabajando en una aplicación básica de autenticación de reacción, en este momento las rutas/registro e/inicio de sesión funcionan cuando ejecuto este repositorio con mi archivo .env.local que contiene variables de autenticación de base de fuego. https://github.com/MartinBarker/react-auth-app

Estoy tratando de hacer que la ruta '/' que apunta a Dashboard solo sea accesible para un usuario que haya iniciado sesión actualmente, y si un usuario no ha iniciado sesión pero intenta acceder a la ruta '/', será redirigido a la página '/iniciar sesión'.

Pero cada vez que uso la ruta

 <PrivateRoute exact path="/" element={Dashboard} />

mi consola de devtools de Chrome muestra una página en blanco con mensajes de error:

 index.tsx:24 Uncaught Error: [PrivateRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

mi PrivateRoute.js se ve así:

 // This is used to determine if a user is authenticated and // if they are allowed to visit the page they navigated to. // If they are: they proceed to the page // If not: they are redirected to the login page. import React from 'react' import { Navigate, Route } from 'react-router-dom' import { useAuth } from '../Contexts/AuthContext' const PrivateRoute = ({ component: Component, ...rest }) => { // Add your own authentication on the below line. //const isLoggedIn = AuthService.isLoggedIn() const { currentUser } = useAuth() console.log('PrivateRoute currentUser = ', currentUser) return ( <Route {...rest} render={props => currentUser ? ( <Component {...props} /> ) : ( //redirect to /login if user is not signed in <Navigate to={{ pathname: '/login'}} /> ) } /> ) } export default PrivateRoute

No estoy seguro de por qué ocurre este error, se agradece cualquier ayuda.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Este comportamiento parece haber cambiado en ReactRouter V6. Esta es la solución que se nos ocurrió para un proyecto.

Ruta privada *Volviendo a crear el código de pregunta de los usuarios

 import React from 'react' import { Navigate, Route } from 'react-router-dom' import { useAuth } from '../Contexts/AuthContext' const PrivateRoute = ({ children }) => { // Add your own authentication on the below line. //const isLoggedIn = AuthService.isLoggedIn() const { currentUser } = useAuth() console.log('PrivateRoute currentUser = ', currentUser) return ( <> { currentUser ? ( children ) : ( //redirect to /login if user is not signed in <Navigate to={{ pathname: '/login'}} /> ) } </> ) } export default PrivateRoute

Texto mecanografiado * Nuestra implementación de código real de este problema

 const PrivateRoute: React.FC = ({ children }) => { const navigate = useNavigate(); const { isAuthenticated, isAuthLoading } = useAuth(); const { user, isLoadingUser } = useContext(UserContext); // Handle users which are not authenticated // For example redirect users to different page // Show loader if token is still being retrieved if (isAuthLoading || isLoadingUser) { // TODO: show full page loader return ( <div>Loading...</div> ); } // Proceed with render if user is authenticated return ( <> {children} </> ); };

enrutador

 <Router> <Routes> <Route path={routes.user.accountSignup.path} element={ <PrivateRoute> <AccountSignup /> </PrivateRoute> } /> </Routes> </Router>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!