这是会话 Flash 消息的一个很好的用例 ????
https://remix.run/docs/en/v1/api/remix#sessionflashkey-value https://remix.run/docs/en/v1/api/remix#sessionflashkey-value
该文档提供了一个很好的示例,但其背后的想法是:
- 在 Index 的操作中获取表单数据
- 将字符串化数据存储在会话 cookie flash 消息中
- 使用重定向功能返回响应(从 remix 导入的帮助程序,为您创建响应重定向)
- 在NewPage的加载器中,读取会话cookie消息并返回它。不要忘记提交您的会话,它会为您删除此闪存消息
- 在组件中使用 useLoaderData 挂钩来获取加载器的返回数据
//sessions.server.ts
import { createCookieSessionStorage } from "remix";
// https://remix.run/docs/en/v1/api/remix#createcookiesessionstorage
const { getSession, commitSession, destroySession } =
createCookieSessionStorage({
cookie: {
name: "__session",
secrets: ["r3m1xr0ck5"], // should be a process.env.MY_SECRET
sameSite: "lax",
},
});
import { ActionFunction, Form } from "remix";
import { getSession, commitSession } from "./sessions";
export const action: ActionFunction = async ({ request }) => {
// const formData = await request.formData();
// Get session
const session = await getSession(
request.headers.get("Cookie")
);
session.flash("myMessageKey", "Hello world!");
return redirect("/new-page", {
headers: {
"Set-Cookie": await commitSession(session),
},
});
};
export default function Index() {
return (
<div>
<Form method="post">
<input type="text" id="name" name="name" />
<button type="submit">Submit</button>
</Form>
</div>
);
}
import { LoaderFunction } from "remix";
import { getSession, commitSession } from "./sessions";
export const loader: LoaderFunction = async ({ request }) => {
const formData = await request.formData();
// Get message here
const session = await getSession(
request.headers.get("Cookie")
);
const message = session.get("myMessageKey") || null;
return json(
{ message },
{
headers: {
"Set-Cookie": await commitSession(session), //will remove the flash message for you
// "Set-Cookie": await commitSession(session, { maxAge: SESSION_MAX_AGE }), //re set max age if you previously set a max age for your sessions.
},
}
);
};
export default function NewPage() {
const { message } = useLoaderData();
return <div>New Page {message}</div>;
}