翻翻過去那場雪
2023-08-18 17:11:31
我剛剛在我的應(yīng)用程序中實現(xiàn)了基于路由器的代碼分割(延遲加載)。AFAIK,當實現(xiàn)延遲加載時,訪問頁面的用戶將僅加載整個包的某個塊,而不會加載其他內(nèi)容。那么,有沒有一種方法可以讓React在初始頁面加載后開始加載其他組件,這樣用戶跳轉(zhuǎn)到另一個頁面時就不必等待呢?const App = React.lazy(() => import('./components/home/App'))const Game = React.lazy(() => import('./components/game/Game'))const Custom = React.lazy(() => import('./components/custom/Custom'))const Credits = React.lazy(() => import('./components/credits/Credits'))const Rules = React.lazy(() => import('./components/rules/Rules'))const NotFound = React.lazy(() => import('./components/404/404'))
1 回答

侃侃無極
TA貢獻2051條經(jīng)驗 獲得超10個贊
我現(xiàn)在意識到我正在嘗試做的事情叫做“預(yù)加載組件”。
// component/home/App.js
// Preloading Game.js from App.js
const lazyWithPreload = (factory) => {
? ? const Component = React.lazy(factory)
? ? Component.preload = factory
? ? return Component
}
?
const Game = lazyWithPreload(() => import('../game/Game'))
?
const App = () => {
? ? React.useEffect(() => {
? ? ? ? Game.preload()
? ? }, [])
? ? return (<div>Something cool</div>)
}
lazyWithPreload隨時隨地預(yù)加載組件,包括加載初始頁面時(這解決了我的問題)。
添加回答
舉報
0/150
提交
取消