当用户未登录时重定向登录.Reactjs

Iva*_*kiv 27 authentication redirect routes ecmascript-6 reactjs

我的应用看起来像:

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>  
  }
Run Code Online (Sandbox Code Playgroud)

如果用户访问/ game下的页面并且未登录,我想将它们重定向到登录页面.

如何在所有路由器中以优雅的方式做到这一点?

blu*_*xty 61

请参阅此答案/sf/answers/3022006081/.也许有比我更多代表的人可以将此标记为重复.

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

这一点也在此链接的反应路由器培训文档中进行了描述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>
Run Code Online (Sandbox Code Playgroud)

和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
Run Code Online (Sandbox Code Playgroud)