Remix defer() 在最基本的示例中无法按预期工作。它在传输数据之前等待所有承诺

问题描述 投票:0回答:1

我有关键数据和非关键数据。两者都是通过加载器提供的。我想使用 defer 将非关键数据作为承诺传输。

给出以下示例,我预计“quickAndCritical”将在大约 1 秒后渲染,“慢速”将在大约 2 秒后渲染。 但实际上页面保持空白大约 3 秒,然后渲染两者。

我在这里犯了错误吗?我将不胜感激任何帮助!

import React, { Suspense } from "react";
import { defer } from "@remix-run/node";
import { Await, Links, Meta, useLoaderData } from "@remix-run/react";
import type { LoaderFunction, LoaderFunctionArgs } from "@remix-run/node";

export function quickAndCritical() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("quickAndCritical");
    }, 1000);
  });
}

export function slowAndDeferrable() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("slow");
    }, 3000);
  });
}

export const loader: LoaderFunction = async ({ request }: LoaderFunctionArgs) => {
  const critical = await quickAndCritical();
  const canBeDeferred = slowAndDeferrable();

  return defer({
    critical,
    canBeDeferred,
  });
};

export default function App() {
  const { critical, canBeDeferred } = useLoaderData();

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        {critical}
        <br></br>
        <br></br>
        <Suspense fallback={null}>
          <Await resolve={canBeDeferred}>{(resolvedData) => <div>{resolvedData}</div>}</Await>
        </Suspense>
      </body>
    </html>
  );
}

reactjs async-await shopify-app remix deferred-loading
1个回答
0
投票

根据Remix Docs,您需要在等待任何其他承诺之前启动延迟数据的承诺。

交换第 1 行和第 2 行应该可以解决问题。

export const loader: LoaderFunction = async ({ request }: LoaderFunctionArgs) => {
  const canBeDeferred = slowAndDeferrable();
  const critical = await quickAndCritical();
  

  return defer({
    critical,
    canBeDeferred,
  });
};
© www.soinside.com 2019 - 2024. All rights reserved.