当用户未登录时,重定向到登录. React.js [英] When user is not logged in redirect to login. Reactjs

查看:945
本文介绍了当用户未登录时,重定向到登录. React.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序如下:

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下的页面并且未登录,我想将他们重定向到登录名 页面.

If the user visits a page under /game and is not logged in, I want to redirect them to the login page.

如何在所有路由器中做到这一点?

推荐答案

查看此答案 https://stackoverflow.com/a/43171515/208079 .也许代表比我更多的人可以将此标记为重复.

See this answer https://stackoverflow.com/a/43171515/208079. Perhaps someone with more rep than me can mark this as a duplicate.

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

The basic idea is to wrap routes that require authentication with a custom component (PrivateRoute in the example below). PrivateRoute will use some logic to determine if the user is authenticated and then either; allow the requested route to render, or redirect to the login page.

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

This is also described in the react-router training docs at this link https://reacttraining.com/react-router/web/example/auth-workflow.

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

Here is an implementation using the above as inspiration.

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

In App.js (or where your routing is happening)

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组件

And the PrivateRoute Component

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

这篇关于当用户未登录时,重定向到登录. React.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆