react异步加载组件
1. 创建 asyncComponent 异步加载工具
import React from 'react' function asyncComponent(loadComponent){ class AsyncComponent extends React.Component{ static defaultProps = { loading: <p>Loading</p>, error: <p>Error</p> } constructor(props){ super(props) this.loaad = this.load.bind(this) this.state = { module: null } } componentWillMount(){ this.load(this.props) } load(props){ this.setState({ module: props.loading }) loadComponent() .then( m=> { let Module = m.default ? m.default: m this.setState({ module: <Module {...props}/> }) }).catch((error)=>{ this.setState({ module: props.error }) console.log(error) }) } render(){ return this.state.module } } return AsyncComponent } export default asyncComponent
2. 异步加载react组件
let Widget = asyncComponent(()=>import(`widgets/${type.charAt(0).toUpperCase()}${type.slice(1)}Chart`))
<Widget />
F12 查看资源network发现在异步组件mounted时浏览器会发送对应组件模块的资源请求