react18 +reactrouter6 +ts 懒加载白屏

zoufengrui
  • 486

新搭建的一个react框架,想要使用lazy进行懒加载,但是启动后白屏
image.png

项目来源:vite初始化的react+ts模板,
自行引入的reactrouter6

项目结构:
image.png

router.ts配置文件:

import {lazy, createElement} from "react"

const routes: Array<any> = [
  {
    path: "/main",
    component: lazy(()=> import("../containers/Main")),
  }
]

export {routes}

App.tsx

import './App.css'
import {routes} from "./router"
import { useRoutes } from 'react-router-dom'

function App() {
  const elements = useRoutes(routes)
  console.log("elements", elements)
  return elements
}

export default App

main.tsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import { HashRouter as Router} from "react-router-dom"
import App from './App'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>
)

请问问题出在哪里,如何解决呢?

问题补充:

采用之后报如下错误:
image.png

回复
阅读 1.6k
1 个回答
_usw
  • 3.7k
✓ 已被采纳

routes.ts得改一下,是element不是component,其次lazy的结果不符合element的类型要求

import {lazy, createElement, Suspense} from "react"
const LazyMain = lazy(()=> import("../containers/Main"))
const routes: Array<any> = [
  {
    path: "/main",
    element: <Suspense fallback={<>...</>}><LazyMain/></Suspense>,
  }
]

export {routes}

===== 官网给了相关的例子,可以查看一下
https://reactrouter.com/docs/...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏