lazy: 内置方法
Suspense(悬念的意思): 内置组件,挂载到 React
lazy 是 React 提供给你的懒(动态)加载组件的方法 React.lazy()
lazy: 接受一个动态导入组件函数
export default xxx
Suspense 目前只和 lazy 配合实现组件等待加载指示器的功能
服务端渲染,不支持 lazy、Suspense ,得用 Loadable Components 替代
import Loading from "./15.Loading";
const MainComponent = React.lazy(() => import('./15.Main.jsx'));
const Main2Component = React.lazy(() => import('./15.Main2.jsx'));
class App extends React.Component {
render() {
return (
<React.Suspense fallback={ <Loading /> }>
<MainComponent />
<Main2Component />
</React.Suspense>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
class Loading extends React.Component {
render() {
return <div>Loading...</div>
}
}
export default Loading;
class Main extends React.Component {
render() {
return <div>Main</div>
}
}
export default Main;
class Main2 extends React.Component {
render() {
return <div>Main2</div>
}
}
export default Main2
import React, { Component, lazy, Suspense } from 'react';
import Loading from './Loading.jsx';
import { Switch, Route } from 'react-router';
const MainComponent = lazy(() => import('./Main.jsx'));
class App extends Component {
render() {
return (
<div className="App">
<Suspense fallback={ <Loading /> }>
<Switch>
<Route path="/page1" component={ lazy(() => import('./views/Page1')) } />
<Route path="/page2" component={ lazy(() => import('./views/Page2')) } />
<Route path="/page3" component={ lazy(() => import('./views/Page3')) } />
</Switch>
</Suspense>
</div>
);
}
}
export default App;
import React from 'react';
class Main extends React.Component {
render() {
return <div>Main</div>
}
}
export default Main;
import React from 'react';
class Loading extends React.Component {
render() {
return <div>Loading</div>
}
}
export default Loading;
import React, { Component} from 'react';
class Page1 extends Component {
render() {
return <div>Page1</div>
}
}
export default Page1;