主體
分支
main (6.23.1)dev
版本
6.23.1v4/5.xv3.x
shouldRevalidate

shouldRevalidate

類型宣告
interface ShouldRevalidateFunction {
  (args: ShouldRevalidateFunctionArgs): boolean;
}

interface ShouldRevalidateFunctionArgs {
  currentUrl: URL;
  currentParams: AgnosticDataRouteMatch["params"];
  nextUrl: URL;
  nextParams: AgnosticDataRouteMatch["params"];
  formMethod?: Submission["formMethod"];
  formAction?: Submission["formAction"];
  formEncType?: Submission["formEncType"];
  text?: Submission["text"];
  formData?: Submission["formData"];
  json?: Submission["json"];
  actionResult?: any;
  unstable_actionStatus?: number;
  defaultShouldRevalidate: boolean;
}

此函式允許您選擇不重新驗證路由的 loader 作為最佳化。

此功能僅在使用資料路由時才有效,請參閱 選擇路由

有幾個實例會重新驗證資料,自動讓您的 UI 與資料保持同步

  • 在透過 action 呼叫後
    • <Form><fetcher.Form>useSubmitfetcher.submit
    • 啟用 future.unstable_skipActionErrorRevalidation 標記時,如果 action 傳回或引發 4xx/5xx Responseloaders 預設不會重新驗證
    • 您可以透過 shouldRevalidateunstable_actionStatus 參數選擇在這些情況下重新驗證
  • 透過 useRevalidator 觸發明確重新驗證時
  • 針對已渲染路由,當 URL 參數 變更時
  • 當 URL 搜尋參數變更時
  • 當導覽至與目前 URL 相同的 URL 時

如果在路由中定義 shouldRevalidate,它會先檢查函式,然後再呼叫路由 loader 以取得新資料。如果函式傳回 false,則 不會 呼叫 loader,而該 loader 的既有資料仍會保留在頁面上。

Fetcher 載入也會重新驗證,但由於它們會載入特定 URL,因此不需擔心上述由 URL 驅動的重新驗證情境。Fetcher 載入預設上只會在 action 送出和明確重新驗證的要求後重新驗證。
<Route
  path="meals-plans"
  element={<MealPlans />}
  loader={loadMealPlans}
  shouldRevalidate={({ currentUrl }) => {
    // only revalidate if the submission originates from
    // the `/meal-plans/new` route.
    return currentUrl.pathname === "/meal-plans/new";
  }}
>
  <Route
    path="new"
    element={<NewMealPlanForm />}
    // `loadMealPlans` will be revalidated after
    // this action...
    action={createMealPlan}
  />
  <Route
    path=":planId/meal"
    element={<Meal />}
    // ...but not this one because origin the URL
    // is not "/meal-plans/new"
    action={updateMeal}
  />
</Route>

請注意,這僅適用於已載入、目前已呈示且會在新 URL 中繼續呈示的資料。新 URL 中的新路線和擷取功能的資料將始終在初始時擷取。

使用這個 API 使你的 UI 有風險會與資料不同步,敬請小心使用!