当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 关于react-router的几种配置方式详解

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文介绍关于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找到对应的映射。

  1. 这里需要注意的是indexroute这个有点不一样的标签,这个的作用就是匹配'/'的路径,因为在渲染app整个组件的时候,可能它的children还没渲染,就已经有'/'页面了,你可以把indexroute当成首页。
  2. 嵌套路由就直接在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中有实现代码拆分功能的工具来用,其实就是把路由拆分成小代码块,然后按需加载。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网