分支
主 (6.23.1)開發
版本
6.23.1v4/5.xv3.x
索引查詢參數

索引查詢參數

當提交表單時,您可能會在應用程式的網址中發現一個狂野的?index出現。

由於嵌套路由,路由層次結構中的多個路由可以符合網址。與在建立 UI 時會呼叫所有符合路由載入器的導覽不同,當提交表單時,只會呼叫一個動作

由於索引路由與它們的父類共用相同的網址,?index參數讓您可以消除兩者之間的歧義。

例如,考量下列路由器和表單

createBrowserRouter([
  {
    path: "/projects",
    element: <ProjectsLayout />,
    action: ProjectsLayout.action,
    children: [
      {
        index: true,
        element: <ProjectsIndex />,
        action: ProjectsPage.action,
      },
    ],
  },
]);

<Form method="post" action="/projects" />;
<Form method="post" action="/projects?index" />;

?index參數將會提交至索引路由,而不含索引參數的動作將會提交至父路由。

當一個<Form>在沒有action的索引路由中被渲染時,?index參數將會自動附加,以便表單會發佈至索引路由。下列表單在提交時,會發佈至/projects?index,因為它在專案索引路由的內容中被渲染

function ProjectsIndex() {
  return <Form method="post" />;
}

如果您將程式碼移至ProjectsLayout路由,它將會改為發佈至/projects

這適用於<Form>及其所有表親

let submit = useSubmit();
submit({}, { action: "/projects" });
submit({}, { action: "/projects?index" });

let fetcher = useFetcher();
fetcher.submit({}, { action: "/projects" });
fetcher.submit({}, { action: "/projects?index" });
<fetcher.Form action="/projects" />;
<fetcher.Form action="/projects?index" />;
<fetcher.Form />; // defaults to the route in context