【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
相关推荐
zhensherlock8 分钟前
Protocol Launcher 系列:Trae AI 编辑器的深度集成
javascript·人工智能·vscode·ai·typescript·编辑器·ai编程
吠品18 分钟前
Vue项目Moment.js引入优化:全局挂载与按需引入的深度解析与最佳实践
前端·javascript·vue.js
不甜情歌20 分钟前
JS 类型判断不用愁:4 种方法,覆盖所有场景
前端·javascript
ETA827 分钟前
状态管理没那么复杂:手写实现 Zustand 核心逻辑
前端·react.js
FanetheDivine31 分钟前
在react中使用signal
vue.js·react.js
共享家952736 分钟前
单例模式( 饿汉式与懒汉式 )
开发语言·javascript·ecmascript
cmd38 分钟前
前端基础必看:JS 变量提升 & 函数提升完整解析
前端·javascript
小金鱼Y38 分钟前
前端必看:this 不是玄学!5 大绑定规则帮你永久告别 this 困惑
前端·javascript·面试
We་ct1 小时前
React Hooks 核心原理
前端·react.js·链表·前端框架·reactjs·hooks