栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

当用户未登录时,重定向到登录。Reactjs

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

当用户未登录时,重定向到登录。Reactjs

基本思想是使用自定义组件(在下面的示例中为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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号