React Code Splitting - 在初始页面后加载其他组件

React Code Splitting - Load other component after initial page

我刚刚在我的应用程序中实现了基于路由器的代码拆分(延迟加载)。 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'))

多亏了Yash Joshi的启迪,我现在才明白我要做的就是“预加载一个组件”。

// 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 随时随地预加载组件,包括加载初始页面时(这解决了我的问题)。

来源:https://medium.com/hackernoon/lazy-loading-and-preloading-components-in-react-16-6-804de091c82d