见答案https://stackoverflow.com/a/43171515/208079.也许有比我更具代表性的人可以将其标记为复制品.
下面的示例中,idea组件需要使用Privater来包装身份验证.PrivateRoute将使用一些逻辑来确定用户是否经过身份验证,然后;允许呈现请求的路由,或重定向到登录页面.
此链接https://reacttraining.com/react-router/web/example/auth-workflow的react router培训文档中也描述了这一点.
以下是一个以上述为灵感的实现.
应用程序内.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>
还有私密路由部分
// 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