useRevalidator
除了正常数据突变(例如窗口焦点或间隔轮询)之外,还会因其他原因重新验证页面上的数据。
¥Revalidate the data on the page for reasons outside of normal data mutations like window focus or polling on an interval.
import { useRevalidator } from "@remix-run/react";
function WindowFocusRevalidator() {
const revalidator = useRevalidator();
useFakeWindowFocus(() => {
revalidator.revalidate();
});
return (
<div hidden={revalidator.state === "idle"}>
Revalidating...
</div>
);
}
Remix 已经在调用操作时自动重新验证页面上的数据。如果你发现自己使用它来对数据进行常规的 CRUD 操作以响应用户交互,那么你可能没有利用其他 API(例如 <Form>
、useSubmit
或 useFetcher
)来自动执行此操作。
¥Remix already revalidates the data on the page automatically when actions are called. If you find yourself using this for normal CRUD operations on your data in response to user interactions, you're probably not taking advantage of the other APIs like <Form>
, useSubmit
, or useFetcher
that do this automatically.
¥Properties
revalidator.state
重新验证的状态。"idle"
或 "loading"
。
¥The state of the revalidation. Either "idle"
or "loading"
.
revalidator.revalidate()
启动重新验证。
¥Initiates a revalidation.
function useLivePageData() {
const revalidator = useRevalidator();
useInterval(() => {
if (revalidator.state === "idle") {
revalidator.revalidate();
}
}, 5000);
}
有关 useInterval
实现的示例,请参阅 此处。
¥See here for a sample useInterval
implementation.
¥Notes
虽然你可以同时渲染多个 useRevalidator
,但其底层是一个单例。这意味着当调用一个 revalidator.revalidate()
时,所有实例都会一起进入 "loading"
状态(或者更确切地说,它们都会更新以报告单例状态)。
¥While you can render multiple occurrences of useRevalidator
at the same time, underneath it is a singleton. This means when one revalidator.revalidate()
is called, all instances go into the "loading"
state together (or rather, they all update to report the singleton state).
当由于其他原因重新验证已在进行中时,调用 revalidate()
会自动处理竞争条件。
¥Race conditions are automatically handled when calling revalidate()
when a revalidation is already in progress for any other reason.
如果在重新验证过程中发生导航,则重新验证将被取消,并从所有加载器请求下一页的新数据。
¥If a navigation happens while a revalidation is in flight, the revalidation will be canceled and fresh data will be requested from all loaders for the next page.