簡體   English   中英

React.lazy 沒有加載任何組件

[英]React.lazy not loading any components

我正在嘗試在 React 應用程序中實現一些代碼拆分。 在這種情況下,這不是絕對必要的,因為它是一個相當小的應用程序,但我認為我會在大型項目中實施之前在低風險環境中嘗試這種技術。

我的代碼有效:

import React from 'react'
import { useUser } from './context/userContext'
import Layout from './components/layout'
import Routes from './components/routes'
import LandingScreen from './components/authApp/LandingScreen'

const App = () => {
  const user = useUser()

  return (
    <>
      {user ? (
        <Layout>
          <Routes />
        </Layout>
      ) : (
        <LandingScreen />
      )}
    </>
  )
}

export default App

例如,如果我嘗試更改任何組件以使用 React.lazy

const LandingScreen = React.lazy(() => import('./components/authApp/landingScreen'))

我的應用程序編譯正常,但瀏覽器中沒有任何組件呈現,並且我收到此錯誤:

index.js:1 The above error occurred in one of your React components:
    in Unknown (at App.js:26)
    in App (at src/index.js:14)
    in UserProvider (at appProvider.js:7)
    in AuthProvider (at appProvider.js:6)
    in AppProviders (at src/index.js:13)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/docs/error-boundaries.html to learn more about error boundaries.

我很感激我在這里做錯了什么的任何線索。 LandingScreen 組件僅呈現一些 div 和我的登錄組件,但即使它僅呈現單個 div,也會發生相同的錯誤。

編輯:將延遲加載的組件包裝在 Suspense 組件中可以修復它。 文檔似乎表明 Suspense 組件是可選的,但也許不是? 任何知道更多並且可以加入的人,將不勝感激。

一個lazy組件應該是一個Suspense的后代,如果你使用Suspense那么你需要提供一個fallback

好的,在文檔中

const App = () => {
  const user = useUser()

  return (
    <Suspense fallback={<></>}>
      {user ? (
        <Layout>
          <Routes />
        </Layout>
      ) : (
        <LandingScreen />
      )}
    </Suspense>
  )
}

注意:您不必使用Suspense ,但如果你不這樣做,那么你已經基本上得到了與自己徹底改造它ErrorBoundary ,所以它更容易只是使用它。

懸疑陷阱

如果Suspense下的任何組件在渲染時掛起(例如,是lazy ),那么直到最近的 Suspense 的整個組件樹都會卸載並在組件准備好時重新安裝。 這可能是一個巨大的陷阱。

懸念實際上在做什么?

React 一直在拋出一個想法,即組件可以throw一個 Promise - throw在這里非常重要,它不能返回一個Promise ,它必須throw它 - 以表明它是“異步的”。 如果最近的ErrorBoundary (它是Suspense )捕捉到一個Promise ,那么它會顯示它的fallback道具。 當它捕獲的Promise解析時,它會呈現它的children ——當你考慮它實際在做什么時,這非常簡單。

我說它一直在玩這個想法,因為即使他們已經為Suspense實現了它,他們也正在考慮將它作為數據加載的 API,事實上,人們已經證明你現在可以這樣使用它(可以現在找不到鏈接,但它超級酷)。

用於數據獲取的 API 有望在不久的將來正式化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM