[英]How to handle loading times when a user clicks a Link or NavLink in remix run
I am building an app with remix run and using nested components.我正在构建一个带有 remix run 并使用嵌套组件的应用程序。 When you click a NavLink or Link that loads a component that has a loader function to load data from an api, it can be very slow to get the response and render to the user.
当您单击 NavLink 或加载具有加载器 function 的组件的链接以从 api 加载数据时,获取响应和呈现给用户的速度可能非常慢。 Ideally I would like the URL in the browser to change immediately on click and to load an animation while the component is loading.
理想情况下,我希望浏览器中的 URL 在单击时立即更改,并在加载组件时加载 animation。 I know how I could implement the loading animation with react and the useEffect hook, however I'm not sure how you'd do this with remix and the Link/NavLink tags.
我知道如何使用 react 和 useEffect 挂钩实现加载 animation,但是我不确定您如何使用 remix 和 Link/NavLink 标签执行此操作。
Remix tries to emulate the browser behaviour when navigating, so it doesn't change the URL until the loader has resolved. Remix 尝试在导航时模拟浏览器行为,因此在加载程序解析之前它不会更改 URL。
However, you can improve the UX by showing some loading UI with useNavigation
.但是,您可以通过使用
useNavigation
显示一些加载 UI 来改进 UX。
export default function App() {
const navigation = useNavigation();
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
{navigation.state !== "idle" ? <div>Loading...</div> : null}
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}
If the data in your loader in extremely slow and you're unable to speed it up, you might want to show fallback UI such as a skeleton which can be done withdefer
.如果加载程序中的数据速度极慢并且您无法加快速度,您可能希望显示后备 UI,例如可以使用
defer
完成的骨架。
export function loader({ params }: LoaderArgs) {
return defer({
// NOTE: `getFoo` isn't awaited
foo: getFoo()
});
}
export default function Component() {
const data = useLoaderData<typeof loader>();
return (
<main>
<h1>Foo</h1>
<Suspense fallback={<div>Skeleton UI...</div>}>
<Await
resolve={data.foo}
errorElement={
<div>Error loading foo</div>
}
>
{(foo) => (
<div>
{JSON.stringify(foo, null, 2)}
</div>
)}
</Await>
</Suspense>
</main>
);
}
The following seems to hold the answers:以下似乎包含答案:
import { useNavigation } from "@remix-run/react";
function SomeComponent() {
const navigation = useNavigation();
navigation.state;
navigation.location;
navigation.formData;
navigation.formAction;
navigation.formMethod;
}
You appear to be able to hook into the navigation.state which changes from idle to loading when a link/NavLink has been clicked.您似乎能够连接到 navigation.state,当单击链接/NavLink 时,它会从空闲状态变为加载状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.