私のアプリは次のようになります:
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の下のページにアクセスしてログインしていない場合、ログインページにリダイレクトしたいと思います。
すべてのルーターでそれをエレガントな方法で行う方法
この回答を参照してください https://stackoverflow.com/a/43171515/208079 おそらく、私よりも担当者が多い人は、これを重複としてマークできます。
基本的な考え方は、認証を必要とするルートをカスタムコンポーネント(以下の例では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>
そして、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