【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
相关推荐
天下代码客27 分钟前
使用electronc框架调用dll动态链接库流程和避坑
前端·javascript·vue.js·electron·node.js
冰暮流星1 小时前
javascript之数组
java·前端·javascript
xkxnq2 小时前
第五阶段:Vue3核心深度深挖(第74天)(Vue3计算属性进阶)
前端·javascript·vue.js
三小河2 小时前
Agent Skill与Rules的区别——以Cursor为例
前端·javascript·后端
Hilaku2 小时前
不要在简历上写精通 Vue3?来自面试官的真实劝退
前端·javascript·vue.js
三小河2 小时前
前端视角详解 Agent Skill
前端·javascript·后端
颜酱2 小时前
二叉树遍历思维实战
javascript·后端·算法
鹏多多2 小时前
移动端H5项目,还需要react-fastclick解决300ms点击延迟吗?
前端·javascript·react.js
不想秃头的程序员2 小时前
Vue3 封装 Axios 实战:从基础到生产级,新手也能秒上手
前端·javascript·面试
空白诗3 小时前
React Native 鸿蒙跨平台开发:react-native-svg 矢量图形 - 自定义图标与动画
react native·react.js·harmonyos