当前位置: 首页 > 面试题库 >

当用户未登录时,重定向到登录。Reactjs

贺博厚
2023-03-14
问题内容

我的应用看起来像:

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

如果用户访问/ game下的页面并没有登录,我想将他们重定向到登录页面。

如何在所有路由器中做到优雅?


问题答案:

基本思想是使用自定义组件(在下面的示例中为PrivateRoute)包装需要身份验证的路由。PrivateRoute将使用某种逻辑来确定用户是否已通过身份验证,然后确定是否通过身份验证。允许请求的路由呈现或重定向到登录页面。

在react-router培训文档中的以下链接https://reacttraining.com/react-
router/web/example/auth-workflow
上也对此进行了描述。

这是一个以上述内容为灵感的实现方式。

在App.js中(或发生路由的地方)

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>

还有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 =>
        isLoggedIn ? (
          <Component {...props} />
        ) : (
          <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
        )
      }
    />
  )
}

export default PrivateRoute


 类似资料:
  • 我的应用程序看起来像: 如果用户访问 /game下的页面并且没有登录,我想将他们重定向到登录页面。 如何在所有路由器中以优雅的方式进行?

  • 我是新的编码,请我需要在这个特定的功能的帮助,我将非常感激,如果有人可以帮助。 我在一个android studio项目上工作,在我的活动(假设活动A)我想放置一个按钮,当点击它将打开假设活动B。 我已经能够设置onclick功能,并打算在按钮单击上打开活动B。

  • 记录器文件中的日志- org.springframework.Security.Access.event.loggerlistener-安全授权失败,原因是:org.springframework.Security.Access.accessdeniedexception:访问被拒绝;通过身份验证的主体:org.springframework.security.authentication.ano

  • 问题内容: 我试图制作一个过滤器来阻止未登录的用户访问某些页面。为此,我使用以下方法制作了一个过滤器类 为了允许不需要用户登录的页面,我在init()中创建了一个arraylist url-list。 现在发生了一件非常奇怪的愚蠢的事情。假设我有两个页面home.jsp和dcr.jsp。当我尝试不登录而访问home.jsp时,我已成功重定向至login.jsp,但是当我尝试访问dcr.jsp时,尽

  • 问题内容: 我想设置我的网站,以便如果用户点击该页面并且他们已经登录,它将把他们重定向到主页。如果未登录,它将正常显示。由于登录代码内置在Django中,我该怎么做? 问题答案: 我假设你当前正在使用内置的登录视图, 或你网址中的类似内容。 你可以编写包含默认视图的登录视图。它将检查用户是否已经登录,如果已经登录则重定向,否则使用默认视图。 就像是: 当然可以相应地更改你的网址:

  • 我正在将DNN应用程序从07.00.02升级到07.03.04并在安装后将所有门户重定向到登录页面。所有门户都配置有一个登陆页面,该页面被配置为允许“所有用户”角色视图访问。还有人在升级后遇到过这个问题吗? 2015-02-05 05:45:01 127.0.0.1 GET/-80-127.0.0.1 Mozilla/5.0+(Windows+NT+6.3;+WOW64)+AppleWebKit/