当提交表单时,您可能会发现应用程序的 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
}