react嵌套路由

来源:https://www.cnblogs.com/gxp69/archive/2020/04/16/12711412.html
-Advertisement-
Play Games

1、結構目錄 2、路由配置文件,參照的vue-router config.js import Login from '../view/Login.js'; import System from '../view/System.js'; import Bus from '../view/Bus.js' ...


1、結構目錄

2、路由配置文件,參照的vue-router

config.js

import Login from '../view/Login.js';
import System from '../view/System.js';
import Bus from '../view/Bus.js';
import Bus22 from '../view/Bus22.js';

const routes = [
  {
    path: "/",
    component: Login,
    exact: true,
  },
  {
    path: "/system",
    component: System,
    auth:true,
    routes: [
      {
        path: "/system/bus",
        component: Bus,
        exact: true,
        auth:true,
      },
      {
        path: "/system/bus22",
        component: Bus22,
        exact: true,
        auth:true,
      },
    ]
  }
];
export default routes;

3、路由主體,使用react-router-dom,詳細文檔裡面也有其它的例子和API

import routes from './config';
import React, {Component} from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from "react-router-dom";

/*一級路由*/
class First extends Component {
  render() {
    return (
      <Router>
        <Switch>
          {routes.map((route, i) => {
              if (route.auth) {//根據配置是否檢測登錄
                return (
                  <PrivateRoute key={i} path={route.path}>
                    <route.component/>
                  </PrivateRoute>
                )
              } else {
                return (<RouteWithSubRoutes key={i} {...route} />)
              }
            }
          )}
        </Switch>
      </Router>
    );
  }
}
/*二級路由*/
class SystemRouter extends Component {
  render() {
    return (
        <Switch>
          {routes[1].routes.map((route, i) => {
            if (route.auth) {//根據配置是否檢測登錄
              return (
                <PrivateRoute  key={i} path={route.path}>
                  <route.component/>
                </PrivateRoute>
              )
            } else {
              return (<RouteWithSubRoutes key={i} {...route} />)
            }
          })}
        </Switch>
    );
  }
}

export {
  First, SystemRouter
};
// A special wrapper for <Route> that knows how to
// handle "sub"-routes by passing them in a `routes`
// prop to the component it renders.
/*開放路由*/
function RouteWithSubRoutes(route) {
  return (
    <Route
      exact={route.exact}
      path={route.path}
      render={props => (
        // pass the sub-routes down to keep nesting
        <route.component {...props} routes={route.routes}/>
      )}
    />
  );
}
/*登錄檢測路由*/
function PrivateRoute({children, ...rest}) {
  let isAuthenticated = sessionStorage.auth;
  return (
    <Route
      {...rest}
      render={({location}) =>
        isAuthenticated ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: {from: location}
            }}
          />
        )
      }
    />
  );
}

4、一級路由的使用,在App.js

import React from 'react';
import './App.css';
import {First} from './router/index';

function App() {
  return (
    <First/>
  );
}

export default App;

5、二級路由的使用,在一級路由的組件文件中,本例是System.js

import React,{Component} from 'react';
import {SystemRouter} from '../router/index';
import {
  withRouter
} from "react-router-dom";
import { Menu, Icon } from 'antd';

const { SubMenu } = Menu;
class System extends Component  {
  componentDidMount() {

  }

  handleClick = e => {
    this.props.history.push(e.key)
  };
  render() {
    return (
      <div>
        <header>
          嵌套路由
        </header>
        <Menu
          onClick={this.handleClick}
          style={{ width: 256,float:'left' }}
          defaultSelectedKeys={['1']}
          defaultOpenKeys={['sub1']}
          mode="inline"
        >
          <SubMenu
            key="sub1"
            title={
              <span>
              <Icon type="mail" />
              <span>Navigation One</span>
            </span>
            }
          >
            <Menu.Item key="/system/bus">bus</Menu.Item>
            <Menu.Item key="/system/bus22">bus22</Menu.Item>
          </SubMenu>
      
        </Menu>
        <SystemRouter  style={{ float:'left' }}/>
      </div>
    );
  }
}
export default withRouter(System);

最後來倆效果圖,頁面分三部分,頭部、左側導航、右側內容,切換時只有右側內容變化。

 

 

 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • "概述" "antd pro table" "antd pro table 的主要部分" "表格顯示的配置(綠色框內)" "檢索的配置(紅色框內)" "是否顯示檢索部分" "檢索的內容是如何生效的" "工具欄的配置(黃色框內)" "表格操作信息(藍色框內)" 概述 如果用 react 開發前端, 建 ...
  • <template> <div class="hello"> <div v-for="(list, index) in merge" :key="index" class="box" :id="`box-${index}`"> <h1>{{list.tittle}}</h1> <ul :id="`i ...
  • 引自官方文檔 在微信小程式中存在一類特殊的組件,該類組件是由客戶端創建的原生組件。這些組件有: camera canvas input(僅在focus時表現為原生組件) live-player live-pusher map textarea video 由於原生組件脫離在 WebView 渲染流程 ...
  • Bootstrap4 輪播 菜鳥教程上的案例 <div id="demo" class="carousel slide" data-ride="carousel"> <!-- 指示符 --> <ul class="carousel-indicators"> <li data-target="#dem ...
  • 跟異國他鄉的朋友們微信聊天的時候,經常面臨時差的問題。每次想要確定對方現在是幾點,總是要口算一下,有時忘記具體時差,或者涉及跨天,還得打開瀏覽器查一下,很不方便。有什麼方法可以把朋友們所在城市的時間集中起來隨時供自己查看呢?於是想到了微信小程式。找了找市面上的時間小程式,不是功能太雜就是小廣告太多,... ...
  • Bootstrap4 麵包屑導航(Breadcrumb) <ul class="breadcrumb"> <li class="breadcrumb-item"><a href="#">item1</a></li> <li class="breadcrumb-item"><a href="#">it ...
  • Bootstrap4 卡片 <div class="card"> <div class="card-body">卡片</div> </div> 卡片頭部,內容,底部 <div class="card"> <div class="card-header">卡片頭部</div> <div class=" ...
  • 最近用力軟的框架覺得框架在佈局這塊不是很友好特別是對像css不是很好的程式員來說,大部分大家都是後端程式員。 所以決定集成一個和力軟敏捷框架風格比較一致的佈局插件進來 插件ce-layout ,下載地址https://gitee.com/program_cat/ce-layout @{ ViewDa ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...