- 初始化工程目录
create-react-app demo
- 创建
async-component.js
import React,{ Component } from 'react';
export default (loadComponent, placeholder = null) => {
class AsyncComponent extends Component {
unmount = false
constructor() {
super()
this.state = {
component: null
}
}
componentWillUnmount() {
this.unmount = true
}
async componentDidMount() {
const {default: component} = await loadComponent()
if(this.unmount) return
this.setState({
component: component
})
}
render() {
const C = this.state.component
return (
C ? <C {...this.props}></C> : placeholder
)
}
}
return AsyncComponent
}
- 引用component
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import asyncComponent from './async-component'
const AsyncDemo = asyncComponent(() => import('./demo'));
const Demo2 = asyncComponent(()=>import('./demo2'));
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
<AsyncDemo />
<Demo2 />
</p>
</div>
);
}
}
export default App;
- 可以结合react-router4使用