我刚刚在我的应用程序中实现了基于路由器的代码分割(延迟加载)。AFAIK,当实现延迟加载时,访问页面的用户将仅加载整个包的某个块,而不会加载其他内容。那么,有没有一种方法可以让React在初始页面加载后开始加载其他组件,这样用户跳转到另一个页面时就不必等待呢?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条经验 获得超10个赞
我现在意识到我正在尝试做的事情叫做“预加载组件”。
// 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随时随地预加载组件,包括加载初始页面时(这解决了我的问题)。
添加回答
举报
0/150
提交
取消