【发布时间】:2019-05-06 14:52:56
【问题描述】:
用例:
- DB 包含每个用户可以看到的小部件名称列表
- 每个小部件都是一个 node_module
- 我们需要在 UI 中动态加载小部件节点模块
示例:
import React from 'react'
import axios from 'axios'
import { StaticRouter,Route, Switch, NavLink } from 'react-router-dom';
const AsyncComponent = (moduleName) => {
return require('../node_modules/' + moduleName) //This line is not working if the moduleName is mentioned at runtime, if it is statically mentioned then it works fine.
//or something like
return import('../node_modules/' + moduleName)
}
export default class Dashboard extends React.Component{
state = {
widgets : [],
appIsMounted: false
}
componentDidMount(){
axios.get('/widgets', (response) => { //DB contains list of widgets names for the specific user and there will be node_module for each widget or functionality.
this.setState({
widgets: response.data //list of functionalities or widgets to show in the UI
})
})
}
render(){
return (
<StaticRouter>
<div>
**strong text** {
this.state.widgets && this.state.widgets.map(module => {
return <nav>
<NavLink to={`/${module}`} exact activeClassName="active">{module.module}</NavLink>
</nav>
})
}
</div>
<div>
<Switch>
{
this.state.widgets && this.state.widgets.map(module => {
return <Route path={`/${module}`} exact component={AsyncComponent.bind(this, module)} />
})
}
</Switch>
</div>
</StaticRouter>
)
}
}
如果有人遇到这个问题,请告诉我。
【问题讨论】:
标签: webpack node-modules dynamic-loading