关于react-router的几种配置方式

路由的概念

路由的作用就是将url和函数进行映射,在单页面应用中路由是必不可少的部分,路由配置就是一组指令,用来告诉router如何匹配url,以及对应的函数映射,即执行对应的代码。

react-router

每一门JS框架都会有自己定制的router框架,react-router就是react开发应用御用的路由框架,目前它的最新的官方版本为4.1.2。本文给大家介绍的是react-router相比于其他router框架更灵活的配置方式,大家可以根据自己的项目需要选择合适的方式。

1.标签的方式

下面我们看一个例子:

import { IndexRoute } from 'react-router'

const Dashboard = React.createClass({
  render() {
    return <div>Welcome to the app!</div>
  }
})

React.render((
  <Router>
    <Route path="/" component={App}>
      {/* 当 url 为/时渲染 Dashboard */}
      <IndexRoute component={Dashboard} />
      <Route path="about" component={About} />
      <Route path="inbox" component={Inbox}>
        <Route path="messages/:id" component={Message} />
      </Route>
    </Route>
  </Router>
), document.body)

我们可以看到这种路由配置方式使用Route标签,然后根据component找到对应的映射。

  • 这里需要注意的是IndexRoute这个有点不一样的标签,这个的作用就是匹配'/'
    的路径,因为在渲染App整个组件的时候,可能它的children还没渲染,就已经有'/'页面了,你可以把IndexRoute当成首页。

  • 嵌套路由就直接在Route的标签中在加一个标签,就是这么简单

2.对象配置方式

有时候我们需要在路由跳转之前做一些操作,比如用户如果编辑了某个页面信息未保存,提醒它是否离开。react-router提供了两个hook,onLeave在所有将离开的路由触发,从最下层的子路由到最外层的父路由,onEnter在进入路由触发,从最外层的父路由到最下层的自路由。

让我们看代码:

const routeConfig = [
  { path: '/',
    component: App,
    indexRoute: { component: Dashboard },
    childRoutes: [
      { path: 'about', component: About },
      { path: 'inbox',
        component: Inbox,
        childRoutes: [
          { path: '/messages/:id', component: Message },
          { path: 'messages/:id',
            onEnter: function (nextState, replaceState) {
              //do something
            }
          }
        ]
      }
    ]
  }
]

React.render(<Router routes={routeConfig} />, document.body)

3.按需加载的路由配置

在大型应用中,性能是一个很重要的问题,按需要加载JS是一种优化性能的方式。在React router中不仅组件是可以异步加载的,路由也是允许异步加载的。Route 可以定义 getChildRoutes,getIndexRoute 和 getComponents 这几个函数,他们都是异步执行的,并且只有在需要的时候才会调用。

我们看一个例子:

const CourseRoute = {
  path: 'course/:courseId',

  getChildRoutes(location, callback) {
    require.ensure([], function (require) {
      callback(null, [
        require('./routes/Announcements'),
        require('./routes/Assignments'),
        require('./routes/Grades'),
      ])
    })
  },

  getIndexRoute(location, callback) {
    require.ensure([], function (require) {
      callback(null, require('./components/Index'))
    })
  },

  getComponents(location, callback) {
    require.ensure([], function (require) {
      callback(null, require('./components/Course'))
    })
  }
}

这种方式需要配合webpack中有实现代码拆分功能的工具来用,其实就是把路由拆分成小代码块,然后按需加载。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值