当用户未登录时,重定向到登录。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>
}
如果用户访问/ 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
以上是 当用户未登录时,重定向到登录。Reactjs 的全部内容, 来源链接: utcz.com/qa/426320.html