在被用到时load component;
asyncComponent.js
传入的function为import();
import React,{Component} from 'react';
const asyncComponent = (importComponent)=>{
return class extends Component{
state={
component:null
}
componentDidMount(){
importComponent() //作为一个异步函数传入
.then(cmp=>{
this.setState({component:cmp.default});
});
}
render(){
const C = this.state.component;
return C?<C{...this.props}/>:null;
}
}
}
export default asyncComponent;
Blog.js
用AsyncNewPost替代NewPost;
import asyncComponent from '../../hoc/asyncComponent';
const AsyncNewPost= asyncComponent(()=>{
return import('./NewPost/NewPost');
//动态import
//当该函数执行时,进行import
//当AsyncNewPost被render时,此函数被调用
});
引入Suspense和Route;
import React, { Component ,Suspense} from 'react';
import { BrowserRouter, Route, NavLink } from 'react-router-dom';
使用React.lazy(()=>import(‘’))设置动态引入;
使用Suspense fallback进行load的JSX控制;
此时< Posts />为动态load;
const Posts = React.lazy(()=>import('./containers/Posts')); //必须使用default exports
当进入/posts时,对< Posts />进行动态render;
<Route path="/posts" render={()=>(
<Suspense fallback={<div>Loading...</div>}>
<Posts/>
</Suspense>
)
}/>
const Posts = React.lazy(()=>import('./containers/Posts')); //必须使用default exports
state={show:false};
modeHandler=()=>{
this.setState(prevState=>{
return {show :!prevState.show};
});
};
此时当state.show为true时,post被调用,< Post />被render,则该component被loaded;
return (
<React.Fragment>
<button onClick={this.modeHandler}>Toggle Mode</button>
{this.state.show?(
<Suspense fallback={<div>Loading...</div>}>
<Posts/>
</Suspense>
):<User/>}
</React.Fragment>