從零搭建React框架--第二章react-router-dom、路由嵌套、路由攔截

目錄

引言
第一章:項(xiàng)目創(chuàng)建、antd、less
第二章:路由攔截、路由嵌套
第三章:狀態(tài)管理 Redux
第四章:網(wǎng)絡(luò)請求、代理、mockjs
第五章:webpack配置
第六章:Eslint

源碼地址

https://github.com/dxn920128/cms-base

安裝react-router-dom

npm install  -S react-router-dom@5.3.0 @types/react-router-dom

路由模式

HashRouter:使用的是URL的hash部分(即window.location.hash),來保持頁面的UI與URL的同步。
BrowserRouter:使用HTML5的history API(pushState, replaceState和popState),讓頁面的UI與URL同步。

一級路由

一級路由主要作用判斷是否登錄,未登錄跳轉(zhuǎn)到登錄界面。

     <HashRouter>
      <Switch>
          <Route path="/login" component={Login} />
          <Route
            path="/"
            render={() => {
              //根據(jù)登錄token、登錄有效期等判斷是否登錄。
              if (isLogin()) {
                return <Frame />;
              } else {
                return <Redirect to="/login" />;
              }
            }}
          />
        </Switch>
      </HashRouter>

二級路由

二級路由就是管理系統(tǒng)的功能路由路由。

const routes = [
  {
    path: '/home',
    component: Home
  },
  {
    path: '/404',
    component: Error
  },
  {
    path: '/system-account',
    component: SystemAccount
  },
  {
    path: '/system-permission',
    component: Permission
  }

]
 <Switch location={location}>
        <Redirect exact from="/" to={config.HOME_ROUTER_PATH} />
          {routes.map(route => {
            return <Route component={route.component} key={route.path} path={route.path} />
          })}
          <Redirect to="/404" />
 </Switch>

左側(cè)菜單

 {
    icon: 'Audit',
    name: '首頁',
    menuId: '1',
    type: '0',
    url: '',
    childList: [
      {
        menuId: '2',
        name: '首頁',
        url: '/home',
        type: '1'
      }
    ]
  },
  {
    menuId: '3',
    type: '0',
    icon: 'Audit',
    name: '系統(tǒng)設(shè)置',
    url: '',
    childList: [
      {
        menuId: '4',
        name: '賬號管理',
        type: '1',
        url: '/system-account'
      },
      {
        menuId: '5',
        name: '權(quán)限分配',
        type: '1',
        url: '/system-permission'
      }
    ]
  }
}
    <Menu>
        <Menu.Item key={item.menuId} icon={<UserOutlined />}>
              <Link to={item.url}>{item.name}</Link>
        </Menu.Item>
        <Menu.Item key={item.menuId} icon={<UserOutlined />}>
              <Link to={item.url}>{item.name}</Link>
        </Menu.Item>
        ...
    </Menu>

效果圖

首頁.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容