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

223
Views
Cuando el usuario no ha iniciado sesión redirigir para iniciar sesión. reaccionar

Mi aplicación se parece a:

 class App extends Component { render() { <Router> <div> <Route exact path='/login' component={Login} /> <Route exact path='/game' component={GameContainer} /> <Route exact path='/chat' component={ChatContainer} /> <Route exact path='/info' component={InfoContainer} /> </div> </Router> }

Si el usuario visita una página en /juego y no ha iniciado sesión, quiero redirigirlo a la página de inicio de sesión.

¿Cómo hacerlo de forma elegante en todos los routers?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Vea esta respuesta https://stackoverflow.com/a/43171515/208079 . Tal vez alguien con más representantes que yo pueda marcar esto como un duplicado.

La idea básica es envolver rutas que requieren autenticación con un componente personalizado (PrivateRoute en el ejemplo a continuación). PrivateRoute utilizará alguna lógica para determinar si el usuario está autenticado y luego; permita que la ruta solicitada se muestre o redirija a la página de inicio de sesión.

Esto también se describe en los documentos de capacitación de react-router en este enlace https://reacttraining.com/react-router/web/example/auth-workflow .

Aquí hay una implementación que usa lo anterior como inspiración.

En App.js (o donde está ocurriendo su enrutamiento)

 import React, { Component } from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom' import PrivateRoute from './PrivateRoute' import MyComponent from '../src/MyComponent' import MyLoginForm from '../src/MyLoginForm' <Router> <Route path="/login" component={MyLoginForm} /> <PrivateRoute path="/onlyAuthorizedAllowedHere/" component={MyComponent} /> </Router>

Y el componente PrivateRoute

 // 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 AuthService from './Services/AuthService' import { Redirect, Route } from 'react-router-dom' const PrivateRoute = ({ component: Component, ...rest }) => { // Add your own authentication on the below line. const isLoggedIn = AuthService.isLoggedIn() return ( <Route {...rest} render={props => return isLoggedIn ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> ) } /> ) } export default PrivateRoute
over 4 years ago · Santiago Trujillo 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!