我正在使用Webpack 3.7.1和React 15.6.1,我正在动态加载不同的组件。
module.exports = {
devServer: {
historyApiFallback: true
},
entry: {
app:"./src/index.js",
vendor: [
"axios",
"react",
"react-dom",
"react-redux",
"react-router",
"react-router-dom",
"redux"
]
},
output: {
path: __dirname + '/public/views',
filename: '[name].js',
chunkFilename: '[chunkhash].chunk.js',
publicPath: "/views/"
},
module: {
loaders: [
{
test: /\.js$/,
loader: "babel-loader",
exclude: [/node_modules/, /pdfmake.js$/]
},
{
test: /\.json$/,
loader: "json-loader"
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: Infinity
}),
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
filename: __dirname + "/views/index.ejs",
template: __dirname + "/views/template.ejs",
inject: 'body',
chunks: ['vendor', 'app'],
chunksSortMode: 'manual'
}),
new PreloadWebpackPlugin({
rel: "preload",
include: ["vendor", "app"]
}),
new webpack.optimize.OccurrenceOrderPlugin(),
]
};
/**
* General container of the website
*/
class AppContainer extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log("MOUNTING APP CONTAINER")
}
render() {
const HomePage = AsyncComponent(() =>
import(/* webpackChunkName:"HomePage" */ "../components/homepage/homepage")
);
return (
<div>
<Switch>
<Route exact path="/" component={HomePage} />
</Switch>
</div>
);
}
}
组件本身更复杂(进行API调用并且有更多路由)但是为了堆栈目的将其简化;)
import React, { Component } from "react";
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
}
我想这个问题来自AsyncComponents / chunk一代,因为在使用AsyncCOmponents并将我的代码拆分成块之前我没有遇到这个问题...但是我没有得到它来自的确切位置
答案 0 :(得分:2)
尝试在HomePage
之外移动render
的声明。 render
可以被调用任意次,并且返回的每个组件看起来都与React不同。
/**
* General container of the website
*/
const HomePage = AsyncComponent(() =>
import(/* webpackChunkName:"HomePage" */ "../components/homepage/homepage")
);
class AppContainer extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log("MOUNTING APP CONTAINER")
}
render() {
return (
<div>
<Switch>
<Route exact path="/" component={HomePage} />
</Switch>
</div>
);
}
}
一般来说,我建议不要在React组件中进行异步工作。您的渲染层应该是同步的,以便为您的UI提供可预测的生命周期。