【React】react 使用 lazy 懒加载模式的组件写法,外面需要套一层 Loading 的提示加载组件

react 组件按需加载问题解决

      • [1 错误信息](#1 错误信息)
      • [2 解决方案](#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 的提示加载组件。

javascript 复制代码
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
相关推荐
满栀58515 分钟前
vue动态路由效果
前端·javascript·vue.js·前端框架·vue
jjw_zyfx2 小时前
css vue vite实现闪烁的呼吸效果
javascript·css·vue.js
sunly_2 小时前
React useActionState 的用法详解
前端·javascript·react.js
cyadyx3 小时前
【Three.js】Three.js 中加载 3D 模型
前端·javascript·3d
汉堡大王95273 小时前
前端工程师 TypeScript 上手指南:一条清晰的从入门到精通路线
前端·javascript·react.js
wear工程师3 小时前
防抖为什么会失效?React 面试里的闭包和定时器
javascript·react.js
浅水壁虎3 小时前
vue基础(第四章 Pinia)
前端·javascript·vue.js
张元清4 小时前
React useEventSource Hook:自带断线重连的 Server-Sent Events (2026)
javascript·react.js
光影少年4 小时前
RN 网络请求:Fetch / Axios 封装、超时、拦截器
前端·react native·react.js
铁皮饭盒4 小时前
网页端, 6.5MB人脸识别模型, 谷歌框架, 又快又准
前端·javascript·后端