美文网首页
从零搭建React框架--第二章react-router-dom

从零搭建React框架--第二章react-router-dom

作者: 被偷的贼 | 来源:发表于2021-11-11 08:33 被阅读0次

目录

引言
第一章:项目创建、antd、less
第二章:路由拦截、路由嵌套
第三章:状态管理 Redux
第四章:网络请求、代理、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同步。

一级路由

一级路由主要作用判断是否登录,未登录跳转到登录界面。

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

二级路由

二级路由就是管理系统的功能路由路由。

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>

左侧菜单

 {
    icon: 'Audit',
    name: '首页',
    menuId: '1',
    type: '0',
    url: '',
    childList: [
      {
        menuId: '2',
        name: '首页',
        url: '/home',
        type: '1'
      }
    ]
  },
  {
    menuId: '3',
    type: '0',
    icon: 'Audit',
    name: '系统设置',
    url: '',
    childList: [
      {
        menuId: '4',
        name: '账号管理',
        type: '1',
        url: '/system-account'
      },
      {
        menuId: '5',
        name: '权限分配',
        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

相关文章

网友评论

      本文标题:从零搭建React框架--第二章react-router-dom

      本文链接:https://www.haomeiwen.com/subject/nteuzltx.html