这是另一个解决方案:我们获得所需组件的列表list = ['c1', 'c2', 'c3']
。它可以从 json 文件拉到一个数组中(我使用 redux-store 所以我开始通过 this.props.getForms() 获取表单)。但是您可以手动创建和访问组件列表。
componentDidMount = () => {
//we get elements list from any source to redux-store
this.props.getForms();
//access redux-store to the list
const forms = this.props.configBody.sets;
//make deep object copy
const updatedState = { ...this.state };
updatedState.modules = [];
if (forms) {
//here is the very dynamic import magic: we map the import list and prepare to store the imports in Component`s state
const importPromises = forms.map(p =>
import(`../TemplateOrders/Template${p.order}`)
.then(module => {
updatedState.modules.push(module.default)
})
.catch(errorHandler(p))
)
//wait till all imports are getting resolved
Promise.all(importPromises)
.then(res =>
//then run setState
this.setState({ ...updatedState }, () => {
console.log(this.state);
}))
}
}
render() {
const forms = this.props.configBody.sets;
//we iterate through the modules and React.createElemet`s
const list = this.state.modules
? this.state.modules.map((e, i) =>
createElement(e, { key: forms[i].title }, null)
)
: [];
return (
<Fragment>
<Link to='/'>Home</Link>
<h1>hello there</h1>
//push them all to get rendered as Components
{list.map(e => e)}
</Fragment>
)
}
因此,当您的应用程序加载时,它会拉取所需的module。
我想使用Promise来导入它们,但是module已经是 Promise 了。
在情况下,我们需要从最近的服务器Ajax它们,所以我们需要绑定前的module分割要求(或类似的东西),不知道到底。