react 登陆页面_Vue 转React开发过程 (路由拦截)

相比于vue的路由 react的路由就没有那么好用了

基本上需要登录的项目都需要做路由拦截功能

下面一起来看看react中是怎么实现路由拦截的

APP.js

import React from "react";
import {BrowserRouter as Router, Switch} from 'react-router-dom';
import "./App.css";

// 路由部分 自行拆文件去
import FrontendAuth from './router/FrontendAuth'
import Home from './home/index'
import Login from "./login/index";
import NotFund from "./notFund"
const routes = [
  { path: '/', meta: { title: '首页' }, component: Home, auth: true },
  { path: '/login', meta: { title: '登录' }, component: Login, auth: false },
  { path: '/app', meta: { title: '首页' }, component: Home, auth: true },
  { path: '/404', meta: { title: '404' }, component: NotFund }
]
// 路由部分结束

class App extends React.Component {
  render() {
    return (
      <Router>
        <Switch>
          <FrontendAuth routerConfig={routes}></FrontendAuth>
        </Switch>
      </Router>
    );
  }
}

export default App;

相比于之前 我们封装了一个FrontendAuth组件

FrontendAuth.js

import React from 'react'
import { Route, Redirect } from "react-router-dom";
export default class FrontendAuth extends React.Component {
  constructor (props) {
    super (props)
  }
  render () {
    const { routerConfig, location } = this.props
    const { pathname } = location
    const isLogin = sessionStorage.getItem('username')
    console.log(routerConfig, pathname)
    const currentPath = routerConfig.find(item => item.path === pathname)
    if (currentPath && !currentPath.auth && !isLogin) {
      return (<Route exact path={pathname} component={currentPath.component}></Route>)
    }
    if (isLogin) {
      if (pathname === '/login') {
        // 如果是登陆状态,想要跳转到登陆,重定向到主页
        return (<Redirect to="/app"></Redirect>)
      } else {
        if (currentPath) {
          // 如果路由合法,就跳转到相应的路由
          return (<Route exact path={pathname} component={currentPath.component}></Route>)
        } else {
          // 如果路由不合法,重定向到 404 页面
          return(<Redirect to="/404"/>)
        }
      }
    } else {
      // 非登陆状态下,当路由合法时且需要权限校验时,跳转到登陆页面,要求登陆
      if (currentPath && currentPath.auth) {
        return <Redirect to="/login" />;
      } else {
        // 非登陆状态下,路由不合法时,重定向至 404
        return <Redirect to="/404" />;
      }
    }
  }
}

这样一个简单的路由拦截功能就实现啦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值