React.lazy 和预取组件 [英] React.lazy and prefetching components

查看:46
本文介绍了React.lazy 和预取组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个两步的申请流程,如下所示:

I have a 2 step Application Flow that looks like this:

const Step1 = React.lazy(() => import('./Step1'));
const Step1 = React.lazy(() => import('./Step2'));

<Suspense fallback={<Loading />}>
  <Route path="/step1" render={() => <Step1 />} />
  <Route path="/step2" render={() => <Step2 />} />
</Suspense>

使用 React.lazy,我可以在用户处于 时延迟加载 ,这可以改善初始页面加载.但是,我想在用户使用 时预取 作为优化.是否有使用 React.lazy 执行此操作的 API?

Using React.lazy, I can defer loading <Step2 /> while the user is on <Step1 />, which can improve initial page load. However, I would like to prefetch <Step2 /> while the user is on <Step1 /> as an optimization. Is there an API to do this with React.lazy?

详细说明 - 我正在使用路由器来呈现两步表单.最初,用户将从 /step1 开始.在用户完成中的所有任务后,他们将被路由到路径/step2.此时路由器将渲染 组件.

To elaborate - I'm using a router to render a 2 step form. Initially the user will start on /step1. After the user completes all the tasks in <Step1 /> they will be routed to path /step2. At this point the router will render the <Step2 /> component.

我在询问是否有一种模式可以在用户仍在 上时预取 .

I'm asking if there is a pattern to pre-fetch <Step2 /> while the user is still on <Step1 />.

推荐答案

几天前我也在阅读有关这方面的文章,我喜欢这种方法:

I was also reading about this few days back and I liked this approach:

增强 React.lazy 以具有可用于加载组件的回调.像这样:

Enhance the React.lazy to have a callback that can be used to load the component. Something like this:

function lazyWithPreload(factory) {
  const Component = React.lazy(factory);
  Component.preload = factory;
  return Component;
}

const ComponentToPreload = lazyWithPreload(() => import("./Component"));

/* usage in Component */

ComponentToPreload.preload(); // this will trigger network request to load the component


通过这种方式,您可以在任何地方预加载组件.就像在 click 事件上或在当前组件安装之后一样.

In this way, you can preload the component wherever you want. Like on click event or after the current component has Mounted.

必须阅读原帖:https://medium.com/hackernoon/lazy-loading-and-preloading-components-in-react-16-6-804de091c82d

如果您使用 react-loadable.你可以检查一下:https://github.com/jamiebuilds/react-loadable#preloading

If you are using react-loadable. You can check this: https://github.com/jamiebuilds/react-loadable#preloading

希望这会有所帮助!

这篇关于React.lazy 和预取组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆