action
路由 action
是一個僅限伺服器端使用的函式,用於處理資料變更和其他動作。如果對您的路由發出非 GET
請求(DELETE
、PATCH
、POST
或 PUT
),則會在 loader
之前呼叫 action。
action
與 loader
具有相同的 API,唯一的區別在於它們被呼叫的時間。這使您能夠在單個路由模組中共同放置有關資料集的所有內容:資料讀取、呈現資料的元件以及資料寫入。
import type { ActionFunctionArgs } from "@remix-run/node"; // or cloudflare/deno
import { json, redirect } from "@remix-run/node"; // or cloudflare/deno
import { Form } from "@remix-run/react";
import { TodoList } from "~/components/TodoList";
import { fakeCreateTodo, fakeGetTodos } from "~/utils/db";
export async function action({
request,
}: ActionFunctionArgs) {
const body = await request.formData();
const todo = await fakeCreateTodo({
title: body.get("title"),
});
return redirect(`/todos/${todo.id}`);
}
export async function loader() {
return json(await fakeGetTodos());
}
export default function Todos() {
const data = useLoaderData<typeof loader>();
return (
<div>
<TodoList todos={data} />
<Form method="post">
<input type="text" name="title" />
<button type="submit">Create Todo</button>
</Form>
</div>
);
}
當對 URL 發出 POST
請求時,路由層級結構中的多個路由將與該 URL 匹配。與呼叫所有 loader 來建構 UI 的 GET
請求不同,只會呼叫一個 action。
如果您想要發佈到索引路由,請在 action 中使用 ?index
:<Form action="/accounts?index" method="post" />
action URL | 路由 action |
---|---|
/accounts?index |
app/routes/accounts._index.tsx |
/accounts |
app/routes/accounts.tsx |
另請注意,沒有 action prop 的表單 (<Form method="post">
) 會自動發佈到它們在其中呈現的同一路由,因此只有在您從索引路由本身以外的其他地方發佈到索引路由時,使用 ?index
參數來消除父路由和索引路由之間的歧義才有用。如果您從索引路由發佈到它本身,或從父路由發佈到它本身,則完全不需要定義 <Form action>
,只需省略它即可:<Form method="post">
。
另請參閱