我的当前路线描述如下所示:我的路线之一:
<Route path='auth' component = {AuthenticateContainer} onEnter = {checkAuth}/>
为了分割路径路径的代码,我相信代码可能如下所示:
<Route path="auth" getComponent={(nextState, callback) => {
require.ensure([], function(require) {
callback(null, require('./AuthenticateContainer.js').default);
})
}}/>
但我缺少的是OnEnter checkAuth功能,我该如何包含它?
答案 0 :(得分:0)
如果checkAuth
中有./AuthenticationContainer.js
,则将其移至routes.js
或创建新的js文件并在routes.js中要求它。基本上,在使用onEnter
要求组件之前,必须在getComponent
钩子上运行函数。
我的routes.js看起来像这样 -
import React from 'react';
import { Route } from 'react-router';
export default (store) => {
function requireAuth(nextState, replace) {
if(!store.getState().auth.isAuthenticated) {
replace({
pathname: '/',
state: { nextPathname: nextState.location.pathname }
})
}
}
return { childRoutes: [{
path: '/',
getComponents(location, callback) {
require.ensure(['./containers/App/App.jsx'], function (require) {
callback(null, require('./containers/App/App.jsx').default)
})
},
childRoutes: [{
path: 'about',
onEnter: requireAuth,
getComponents(location, callback) {
require.ensure(['./containers/About/About.jsx'], function (require) {
callback(null, require('./containers/About/About.jsx').default)
})
}
}]
}]
}
};
我不确定您是否可以在checkAuth
内调用require.ensure
并在未经过身份验证的情况下停止加载该组件。按照设计,这是一个糟糕的方法,因为您正在加载组件,然后检查它是否经过身份验证。这否定了代码拆分的好处。
编辑 - 添加webpack.config.js
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js',
chunkFilename: '[id].chunk.js',
},
devtool: 'inline-source-map',
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel'
},
{
test: /\.css?$/,
loaders: [ 'style', 'raw' ],
include: __dirname
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('shared.js')
]
};
module.exports = config;
Webpack构建输出 -
webpack -d --watch
Hash: 08b101d1e95f7633adb4
Version: webpack 1.13.2
Time: 2680ms
Asset Size Chunks Chunk Names
bundle.js 1.05 MB 0, 3 [emitted] main
1.chunk.js 4.15 kB 1, 3 [emitted]
2.chunk.js 3.19 kB 2, 3 [emitted]
shared.js 3.66 kB 3 [emitted] shared.js
bundle.js.map 1.16 MB 0, 3 [emitted] main
1.chunk.js.map 2.32 kB 1, 3 [emitted]
2.chunk.js.map 1.18 kB 2, 3 [emitted]
shared.js.map 3.67 kB 3 [emitted] shared.js
+ 269 hidden modules