反应悬念/懒惰延迟? [英] React suspense/lazy delay?

查看:86
本文介绍了反应悬念/懒惰延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新的React Lazy和Suspense来创建一个后备加载组件。这很好用,但后备只显示几毫秒。有没有办法添加额外的延迟或最短时间,所以我可以在渲染下一个组件之前显示此组件的动画?

I am trying to use the new React Lazy and Suspense to create a fallback loading component. This works great, but the fallback is showing only a few ms. Is there a way to add an additional delay or minimum time, so I can show animations from this component before the next component is rendered?

现在延迟导入

const Home = lazy(() => import("./home"));
const Products = lazy(() => import("./home/products"));

等待组件:

function WaitingComponent(Component) {

    return props => (
      <Suspense fallback={<Loading />}>
            <Component {...props} />
      </Suspense>
    );
}

我可以这样做吗?

const Home = lazy(() => {
  setTimeout(import("./home"), 300);
});


推荐答案

lazy 函数应该返回 {default:...} 的承诺,该对象由 import()返回具有默认导出的模块。 setTimeout 不返回承诺,不能像那样使用。虽然任意承诺可以:

lazy function is supposed to return a promise of { default: ... } object which is returned by import() of a module with default export. setTimeout doesn't return a promise and cannot be used like that. While arbitrary promise can:

const Home = lazy(() => {
  return new Promise(resolve => {
    setTimeout(() => resolve(import("./home"), 300);
  });
});

如果目标是提供最小延迟,这不是一个好的选择,因为这将导致额外的延迟。

If an objective is to provide minimum delay, this isn't a good choice because this will result in additional delay.

最小延迟是:

const Home = lazy(() => {
  return Promise.all([
    import("./home"),
    new Promise(resolve => setTimeout(resolve, 300))
  ])
  .then(([moduleExports]) => moduleExports);
});

这篇关于反应悬念/懒惰延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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