使用对象而非 JSX 来配置路由
曾经的写法:
<Router>
<Route path="/" component={App}>
<IndexRoute component={Dashboard} />
<Route path="about" component={About} />
<Route path="inbox" component={Inbox}>
<Route path="/messages/:id" component={Message} />
{/* 跳转 /inbox/messages/:id 到 /messages/:id */}
<Redirect from="messages/:id" to="/messages/:id" />
</Route>
</Route>
</Router>
高级用法:
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) {
replaceState(null, '/messages/' + nextState.params.id)
}
}
]
}
]
}
]
React.render(<Router routes={routeConfig} />, document.body)
动态路由
Route 可以定义 getChildRoutes,getIndexRoute 和 getComponents 这几个函数。它们都是异步执行,并且只有在需要时才被调用。我们将这种方式称之为 “逐渐匹配”。 React Router 会逐渐的匹配 URL 并只加载该 URL 对应页面所需的路径配置和组件。
改写 routerConfig 时需要将 component 换成 getComponent。
const routeConfig = {
path: '/',
indexRoute: {
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('components/layer/HomePage'))
}, 'HomePage')
},
},
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('components/Main'))
}, 'Main')
},
childRoutes: [
require('./routes/baidu'),
require('./routes/404'),
require('./routes/redirect')
]
}
getComponent 这个方法是异步的,也就是当路由匹配时,才会调用这个方法。
require.ensure 方法是 webpack 提供的方法,这也是按需加载的核心方法。第一个参数是依赖,第二个是回调函数。