React Router v7 已發佈。 查看文件
索引查詢參數

索引查詢參數

您可能會在提交表單時,在應用程式的 URL 中發現一個奇怪的 ?index 出現。

由於巢狀路由的關係,路由層次結構中的多個路由可以匹配 URL。與調用所有匹配路由的loader來建構 UI 的導覽不同,當form被提交時,只會呼叫一個 action

因為索引路由與其父路由共用相同的 URL,?index 參數可讓您區分兩者。

例如,考慮以下表單

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

?index 參數將提交到索引路由,沒有索引參數的action將提交到父路由。

<Form>在沒有action的索引路由中呈現時,將自動附加 ?index 參數,以便表單發佈到索引路由。以下表單提交時,將發佈到 /projects?index,因為它是呈現在專案索引路由的上下文中

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

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

這適用於 <Form> 及其所有相關組件

function Component() {
  const submit = useSubmit();
  submit({}, { action: "/projects" });
  submit({}, { action: "/projects?index" });
}
function Component() {
  const 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
}
文件和範例以 MIT