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 PrivateRouteNo estoy seguro de por qué ocurre este error, se agradece cualquier ayuda.
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 PrivateRouteTexto 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>