我有关键数据和非关键数据。两者都是通过加载器提供的。我想使用 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>
);
}
根据Remix Docs,您需要在等待任何其他承诺之前启动延迟数据的承诺。
交换第 1 行和第 2 行应该可以解决问题。
export const loader: LoaderFunction = async ({ request }: LoaderFunctionArgs) => {
const canBeDeferred = slowAndDeferrable();
const critical = await quickAndCritical();
return defer({
critical,
canBeDeferred,
});
};