App.js:
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';
const Home = lazy(() => import('./Home'));
const Bar = lazy(() => import('./Bar'));
const App = () => (
<Router>
<Suspense fallback={<div>loading</div>}>
<div>
<ul>
<li><Link to="/">Home></Link></li>
<li><Link to="/bar">Bar></Link></li>
</ul>
</div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/bar" component={Bar} />
</Switch>
</Suspense>
</Router>
)
export default App;
Home.js:
import React, { Component } from 'react';
class Home extends Component {
render() {
return (
<div>
Home
</div>
);
}
}
export default Home;
Bar.js:
import React, { Component } from 'react';
class Bar extends Component {
render() {
return (
<div>
Bar
</div>
);
}
}
export default Bar;
本实例github:https://github.com/xutongbao/react-lazy
参考链接:https://dev.to/saigowthamr/how-to-use-react-suspense-and-reactlazy--klg