当前位置:   article > 正文

react-router-dom@6.x使用懒加载

react-router-dom@6.x使用懒加载

App.js

  1. import { useEffect, lazy, Suspense } from 'react'
  2. import { NavLink, Route, Routes, Navigate, useLocation } from 'react-router-dom'
  3. import Loading from './components/Loading/Loading'
  4. import './css/App.css'
  5. const Home = lazy(() => import('./views/Home'))
  6. const About = lazy(() => import('./views/About'))
  7. function App() {
  8. const location = useLocation()
  9. useEffect(() => {
  10. // document.title = location.state.title
  11. if (location.state) {
  12. document.title = location.state.title
  13. } else {
  14. document.title = '组件验证'
  15. }
  16. }, [location.state])
  17. return (
  18. <div className="App">
  19. <div>
  20. <NavLink to="/home" state={{title: '组件验证'}} className="navigation">组件验证</NavLink>
  21. <NavLink to="/about" state={{title: '高阶组件'}} className="navigation">高阶组件</NavLink>
  22. </div>
  23. <Routes>
  24. <Route path='/home' element={<Suspense fallback={<Loading />}><Home /></Suspense>} />
  25. <Route path='/about' element={<Suspense fallback={<Loading />}><About /></Suspense>} />
  26. <Route path='/' element={ <Navigate to="/home" replace /> } />
  27. </Routes>
  28. </div>
  29. );
  30. }
  31. export default App;

Loadin.jsx

  1. import React from 'react'
  2. import { Spin } from 'antd'
  3. export default function Loading() {
  4. return (
  5. <Spin tip="Loading">
  6. <div className="content" />
  7. </Spin>
  8. )
  9. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/520591
推荐阅读
相关标签
  

闽ICP备14008679号