【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
相关推荐
我命由我123451 小时前
React - 验证 Diffing 算法、key 的作用
javascript·算法·react.js·前端框架·html·html5·js
爱上妖精的尾巴7 小时前
8-18 WPS JS宏 正则表达式-边界匹配
开发语言·javascript·正则表达式·wps·jsa
爱上妖精的尾巴7 小时前
8-20 WPS JS宏 正则表达式-懒惰匹配
服务器·前端·javascript
网络点点滴7 小时前
组件通信props方式
前端·javascript·vue.js
weixin_443478517 小时前
flutter组件学习之Flex / Expanded弹性布局组件
javascript·学习·flutter
SuperEugene8 小时前
Excel 上传解析 + 导出实战:Vue+xlsx 避坑指南|Vue生态精选
前端·javascript·vue.js·excel·xlsx·vxetable
Highcharts.js8 小时前
使用Highcharts创建流图(Stream Graph)指南|流动数据的可视化图表与数据艺术表达
javascript·信息可视化·数据可视化·highcharts·可视化图表·流图·stream graph
努力往上爬de蜗牛8 小时前
el-table列表修改某个输入框输入 卡顿问题修改
javascript·vue.js·elementui
湛海不过深蓝8 小时前
【procomponents】根据表单查询表格数据的两种写法
前端·javascript·react.js