react 组件按需加载问题解决
- 1 错误信息
- 2 解决方案
1 错误信息
react 项目在创建 router 路由时,使用 lazy 懒加载时,导致以下报错:
- The above error occurred in the <Route.Provider> component:
- Uncaught Error: A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.
2 解决方案
懒加载模式的组件写法,外面需要套一层 Loading 的提示加载组件。
import React, { lazy } from 'react'
import { Navigate } from 'react-router-dom'// 按需引入
const Home = lazy(() => import('@/views/Home'))
const About = lazy(() => import('@/views/About'))
const User = lazy(() => import('@/views/User'))// 按需引入导致报错:懒加载模式的组件写法,外面需要套一层 Loading 的提示加载组件
const withLoadingComponent = (comp: JSX.Element) => (<React.Suspense fallback={<>Loading</>}>{comp}</React.Suspense>
)const routes = [{path: '/',element: <Navigate to='/home' />},{path: '/home',element: withLoadingComponent(<Home />)},{path: '/about',element: withLoadingComponent(<About />)},{path: '/user',element: withLoadingComponent(<User />)}
]export default routes