React路由的封装

React中路由是这样编写的

    <Switch>
          <Route path='/index' component={Index}></Route>
          <Route exact path='/login' component={login} ></Route>
          <Route exact path='/xqy/:id' component={Xqy}></Route>
          //重定向
          <Redirect from='/' to='/index'></Redirect>
          //404
          <Route path="*" component={notFound}></Route>
        </Switch>

现在要跳的路由很少,还可以接受,一旦后期路由变多,那么这个文件会变的很臃肿,我们可以对他进行封装,让他动态的去渲染路由。

  •  首先编辑路由表,
import { lazy, Suspense } from 'react'


// 一级路由
var Index = lazy(() => import('../views/Index/Index'))
var Login = lazy(() => import('../views/Login/login'))
var Xqy = lazy(() => import('../views/Xqy/xqy'))
var NotFound = lazy(() => import('../views/NotFound/notFound'))
// 二级路由
var home = lazy(() => import('../views/Index/home/home'))
var Cate = lazy(() => import('../views/Index/Cate/cate'))
var Gwc = lazy(() => import('../views/Index/Gwc/gwc'))
var Mine = lazy(() => import('../views/Index/Mine/mine'))

export default [
    {
        path: '/index',
        component: Index,
        children: [
            {
                path: '/index/home',
                component: home,
            },
            {
                path: '/index/cate',
                component: Cate,
            },
            {
                path: '/index/cate',
                component: Cate,
            },
            {
                path: '/index/gwc',
                component: Gwc,
            },
            {
                path: '/index/mine',
                component: Mine,
            },
            {
                from: '/index',
                to: '/index/home',
            },
            {
                path: '*',
                component: NotFound,
            },
        ]
    },
    {
        path: '/login',
        component: Login,
    },
    {
        path: '/xqy/:id',   //动态路由:id占位
        component: Xqy,
    },
    {
        from: '/',
        to: '/index',
    },
    {
        path: '*',
        component: NotFound,
    },

]
  •  封装的代码
import React, { Component, Suspense } from 'react';
import { Route, Redirect, Switch } from 'react-router-dom'
interface RouteItem {
  path?: string,
  component?: any,
  children?: Array<RouteItem>,
  from?: string,
  to?: string
}
interface Props {
  routes: Array<RouteItem>
}
class RouterView extends Component<Props> {
  render() {
    return (
      <Suspense fallback={<div className='loading'>loading...</div>}>
        <Switch>
          {
            this.props.routes.map((item: any, index: any) => {
              // 重定向
              if (item.from) {
                return <Redirect key={index} exact from={item.from} to={item.to || ''}></Redirect>
              }
              else if (item.children) {
                return (
                  // 判断有没有子路由
                  <Route key={index} path={item.path}   render={() => {
                    return < item.component routes={item.children} />
                  }}></Route>
                )

              }
              else {
                return (
                  <Route key={index} path={item.path} component={item.component}></Route>
                )
              }
            })
          }
        </Switch>
      </Suspense>
    );
  }
}

export default RouterView;
  • 一级路由
import routeConfig from './router/routeConfig';//导入路由表
import RouterView from './router/routerView';//导入封装
<RouterView routes={routeConfig}></RouterView>
  • 二级路由
        //在封装中已经把你的二级路由表存储在props中了
      <RouterView routes={this.props.routes} />

    不管是几级嵌套路由,这个封装都可以满足,也与vue中编写路由模式比较像

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
React 路由封装可以通过使用第三方库来实现,最常用的是 React Router。React Router 是一个用于构建单页面应用的路由库,它提供了一些组件和 API,可以让你在 React 应用中实现路由功能。 下面是一个简单的例子,演示如何使用 React Router 进行路由封装: 首先,你需要安装 React Router。在项目根目录下运行以下命令: ``` npm install react-router-dom ``` 然后,在你的应用中导入所需的模块: ```jsx import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; ``` 在你的应用顶层组件中,使用 `<Router>` 组件将整个应用包裹起来: ```jsx function App() { return ( <Router> {/* 这里放置你的其他组件 */} </Router> ); } ``` 接下来,你可以在 `<Router>` 组件内部使用 `<Switch>` 和 `<Route>` 组件来定义路由规则和对应的组件: ```jsx function App() { return ( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> <Route component={NotFound} /> </Switch> </Router> ); } ``` 上述代码中,`<Switch>` 组件会按照定义的顺序依次匹配路由规则,并渲染第一个匹配到的组件。如果都没有匹配到,就会渲染 `<Route>` 组件中定义的 `component` 属性为 `NotFound` 的组件。 最后,你可以在各个对应的组件中使用 React Router 提供的导航组件,如 `<Link>`、`<NavLink>` 等,来实现页面之间的跳转: ```jsx import { Link, NavLink } from 'react-router-dom'; function Navbar() { return ( <nav> <ul> <li><NavLink exact to="/">Home</NavLink></li> <li><NavLink to="/about">About</NavLink></li> <li><NavLink to="/contact">Contact</NavLink></li> </ul> </nav> ); } ``` 以上就是一个简单的 React 路由封装的示例,你可以根据自己的需求进行更高级的路由操作和封装。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

她比亚索还快乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值