如何使用子路由文件将不同的feature从主路由文件分离
作者:
张培_ | 来源:发表于
2017-12-17 12:16 被阅读11次
情景描述
- 1.项目中使用按需加载的方式,那么整个路由会被写成一个对象
- 2.这时候针对每一个path,我们就需要一个对象对应他
- 3.打开路由会发现有好几个path的第一个slash中的内容都一样,他们代表的是同一个feature
- 4.之前简书有说过,如果为了保证feature之间的隔离性,我们甚至都把store进行了分离。
- 5.那么为什么不把routes.js文件根据feature分离呢?
这么做优点
- 整个项目的路由文件会变得简洁,只有根据不同feature划分的路由,每个路由的path只会有一级的路由
{
path: 'wmp/create_order',
getComponent(location, callback) {
import('./CreateOrderContainer')
.then(loadRoute(callback))
.catch(errorLoading)
}
},
{
path: 'wmp/orders/:orderId',
getComponent(location, callback) {
import('./WisePortOrderContainer')
.then(loadRoute(callback))
.catch(errorLoading)
}
},
{
path: 'wmp/orders_spike',
getComponent(location, callback) {
import('./WisePortOrderContainer/OfferSelectionStep')
.then(loadRoute(callback))
.catch(errorLoading)
}
}
//变成
{
path: '/mwp',
getChildRoutes(partialNextState, callback) {
import('./containers/MWP/routes')
.then(loadRoute(callback))
.catch(err => errorLoading(err))
}
},
- 对于所有的子路由:去除了重复的代码
//routes.js
{
path: 'create_order',
getComponent(location, callback) {
import('./CreateOrderContainer')
.then(loadRoute(callback))
.catch(errorLoading)
}
},
{
path: 'orders/:orderId',
getComponent(location, callback) {
import('./WisePortOrderContainer')
.then(loadRoute(callback))
.catch(errorLoading)
}
},
{
path: 'orders_spike',
getComponent(location, callback) {
import('./WisePortOrderContainer/OfferSelectionStep')
.then(loadRoute(callback))
.catch(errorLoading)
}
}
做法
- 浏览项目的routes.js文件
- 抽离出所有一级路径相同的对象(在本项目中一级路径相同就等同于是同一个 feature部分)
- 删掉这些对象,然后创建一个兑对象path就只是这个一级路径
- 然后将getComponent方法替换成getChildRoutes
- 在这个feature的目录下面建立一个routes.js文件
- 在getChildRoutes这个方法中将feature的routes.js文件引入即可
- 并在feature的routes.js文件中写从项目的routes.js文件抽出的路径
本文标题:如何使用子路由文件将不同的feature从主路由文件分离
本文链接:https://www.haomeiwen.com/subject/wouywxtx.html
网友评论