我想知道是否有一种方法可以重定向路由或返回Response
带有数据的 a 并使用该函数在另一个页面上获取它loader
。
基本上,我试图使用表单创建一个新对象,并重定向到另一个我想要显示创建成功消息的页面。
这是一个表单页面示例:
我正在尝试在正文中发送消息Response
。
import { ActionFunction, Form } from "remix";
export const action: ActionFunction = async ({ request }) => {
// const formData = await request.formData();
return new Response(JSON.stringify({ message: "Hello world!" }), {
status: 303,
headers: {
Location: "/new-page",
},
});
};
export default function Index() {
return (
<div>
<Form method="post">
<input type="text" id="name" name="name" />
<button type="submit">Submit</button>
</Form>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
此时NewPage
我需要知道是否有办法获取重定向响应上的消息。
import { ActionFunction } from "remix";
export const action: ActionFunction = async ({ request }) => {
const formData = await request.formData();
// Get message here
return {
message: "",
};
};
export default function NewPage() {
return <div>New Page</div>;
}
Run Code Online (Sandbox Code Playgroud)
rph*_*lmr 16
这是会话 Flash 消息的一个很好的用例
https://remix.run/docs/en/v1/api/remix#sessionflashkey-value
该文档提供了一个很好的示例,但其背后的想法是:
//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",
},
});
Run Code Online (Sandbox Code Playgroud)
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>
);
}
Run Code Online (Sandbox Code Playgroud)
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>;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7724 次 |
最近记录: |