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中有实现代码拆分功能的工具来用,其实就是把路由拆分成小代码块,然后按需加载。

猜你喜欢

转载自blog.csdn.net/weixin_43858880/article/details/90600539
今日推荐