¥Index Query Param
提交表单时,你可能会发现应用的 URL 中出现了一个不安全的 ?index
。
¥You may find a wild ?index
appear in the URL of your app when submitting forms.
由于路由嵌套,路由层次结构中的多个路由可以匹配 URL。与导航不同,导航会调用所有匹配的路由 loader
来构建 UI,而提交 form
时只会调用一个操作。
¥Because of nested routes, multiple routes in your route hierarchy can match the URL. Unlike navigations where all matching route loader
s are called to build up the UI, when a form
is submitted only one action is called.
由于索引路由与其父路由共享相同的 URL,因此使用 ?index
参数可以区分两者。
¥Because index routes share the same URL as their parent, the ?index
param lets you disambiguate between the two.
例如,考虑以下表单:
¥For example, consider the following forms:
<Form method="post" action="/projects" />;
<Form method="post" action="/projects?index" />;
?index
参数将提交到 index 路由,不带 index 参数的 action
将提交到父路由。
¥The ?index
param will submit to the index route, the action
without the index param will submit to the parent route.
当在没有 action
的索引路由中渲染 <Form>
时,?index
参数将自动附加,以便表单提交到索引路由。以下表单提交后将发布到 /projects?index
,因为它是在 projects
索引路由的上下文中渲染的:
¥When a <Form>
is rendered in an index route without an action
, the ?index
param will automatically be appended so that the form posts to the index route. The following form, when submitted, will post to /projects?index
because it is rendered in the context of the projects
index route:
function ProjectsIndex() {
return <Form method="post" />;
}
如果你将代码移动到 ProjectsLayout
路由,它将被发布到 /projects
。
¥If you moved the code to the ProjectsLayout
route, it would instead post to /projects
.
这适用于 <Form>
及其所有同类版本:
¥This applies to <Form>
and all of its cousins:
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
}