【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
相关推荐
晚霞的不甘5 小时前
Flutter for OpenHarmony 布局核心:Row 与 Column 深度解析与实战
android·前端·javascript·flutter
Easonmax6 小时前
零基础入门 React Native 鸿蒙跨平台开发:5——横向滚动表格实现
react native·react.js·harmonyos
ethan.Yin6 小时前
element-plus 二次封装遇到的一点疑惑
javascript·vue.js·ecmascript
Ulyanov6 小时前
Impress.js 3D立方体旋转个人年终总结设计与实现
开发语言·前端·javascript·3d·gui开发
榴莲不好吃6 小时前
前端js图片压缩
开发语言·前端·javascript
切糕师学AI6 小时前
Vue 中的 keep-alive 组件
前端·javascript·vue.js
可问春风_ren6 小时前
Git命令大全
前端·javascript·git·后端
她说彩礼65万6 小时前
Jquery总结
前端·javascript·jquery
得一录6 小时前
ES6核心语法
前端·ecmascript·es6
Easonmax6 小时前
零基础入门 React Native 鸿蒙跨平台开发:1——实现基础表格组件
react native·react.js·harmonyos