react前端路由懒加载写法在 React 中,通过使用 React Router 来实现前端路由懒加载是一种常见的做法,以提高应用性能。以下是使用 React Router 实现前端路由懒加载的示例:
使用 React.lazy:
import React, { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));
const Contact = lazy(() => import('./components/Contact'));
const App = () => (
<Router>react router路由传参
<Suspense fallback={<div&</div>}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Suspense>
</Router>
);
export default App;
使用 react-loadable:
如果你想使用react-loadable 来进行懒加载,首先需要安装它:
bash
Copy code
npm install react-loadable
然后,你可以按照以下方式使用:
jsx
Copy code
import Loadable from 'react-loadable';
import LoadingComponent from './LoadingComponent'; // 一个加载中的组件,可自定义
const Home = Loadable({
loader: () => import('./components/Home'),
loading: LoadingComponent,
});
const About = Loadable({
loader: () => import('./components/About'),
loading: LoadingComponent,
});
const Contact = Loadable({
loader: () => import('./components/Contact'),
loading: LoadingComponent,
});
const App = () => (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />    </Switch>
</Router>
);
export default App;
上述两种方法都会在需要时异步加载组件,提高应用性能。Suspense 组件用于在异步加载过程中显示加载中的状态。在以上代码中,当路由切换到相应的页面时,相应的组件会在需要时动态加载。