【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
相关推荐
zithern_juejin7 小时前
new 运算符
javascript
前端毕业班7 小时前
uniapp web 灵活控制 style scoped
前端·javascript·vue.js
张元清7 小时前
在 React 里写动画又不跟渲染周期较劲:useRafFn、useRafState、useFps、useDevicePixelRatio、useUpdate
前端·javascript·面试
光影少年8 小时前
Redux 核心流程:Action、Reducer、Store、Dispatch
前端·react.js·掘金·金石计划
甜味弥漫9 小时前
JavaScript 底层逻辑:从内存视角看原型与原型链
前端·javascript
咪饭只吃一小碗9 小时前
JS this 身世大揭秘:它到底该听谁的?
前端·javascript
周淳APP10 小时前
【前端八股第一弹】
开发语言·前端·javascript·react.js
SmartBoyW10 小时前
撕掉前端黑魔法外衣:用 C++/Java 指针思维硬核拆解 JS 原型链
前端·javascript
不好听61310 小时前
数组去重的六种解法
javascript
ftpeak10 小时前
WebMCP Nexus:让 React 应用成为 AI Agent 可驱动的工具
前端·人工智能·react.js