简体   繁体   English

反应 PrivateRoute 授权路线

[英]React PrivateRoute auth route

I am working on a basic react auth app, right now the routes /signup and /login work when I run this repo with my .env.local file that contains firebase auth variables.我正在开发一个基本的 react auth 应用程序,现在当我使用包含 firebase auth 变量的.env.local文件运行此 repo 时,路由 /signup 和 /login 工作。 https://github.com/MartinBarker/react-auth-app https://github.com/MartinBarker/react-auth-app

I am trying to make it so that the '/' route that points to Dashboard will only be accessible for a user who is currently signed in, and if a user is not signed in but tries to access the '/' route they will be redirected to the '/login' page.我正在尝试使指向仪表板的“/”路由只能由当前登录的用户访问,如果用户未登录但尝试访问“/”路由,他们将重定向到“/登录”页面。

But whenever I use the route但是每当我使用路线时

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

my chrome devtools console shows a blank page with error messages:我的 chrome devtools 控制台显示一个包含错误消息的空白页面:

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

my PrivateRoute.js looks like this:我的 PrivateRoute.js 看起来像这样:

// 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

Im not sure why this error is occurring, any help is appreciated我不确定为什么会发生此错误,感谢您的帮助

This behaviour seems to have changed in ReactRouter V6 here is the solution we came up with for a project.这种行为似乎在 ReactRouter V6 中发生了变化,这是我们为一个项目提出的解决方案。

Private route *Re-creating the users question code私人路线*重新创建用户问题代码

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

Typescript *Our actual code implementation of this issue Typescript *我们这个问题的实际代码实现

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}
    </>
  );
};

Router路由器

<Router>
  <Routes>
    <Route
      path={routes.user.accountSignup.path}
      element={
        <PrivateRoute>
          <AccountSignup />
        </PrivateRoute>
      }
    />
  </Routes>
</Router>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM