英文:
How to push data from one page to another in Remix - React
问题
以下是翻译好的部分:
在组件一中,我有这段代码:
export const loader = async ({ request }: LoaderArgs) => {
const session = await getSession(request);
if (condition === true) {
return redirect("/bye", {
headers: {
"Set-Cookie": await sessionStorage.destroySession(session),
'X-Custom-Header': 'Custom Value',
},
data: {
reason: 'we logged you out because of xyz'
}
});
}
return json({});
};
重定向功能正常工作。但是,我需要在/bye页面上获取这些数据。到目前为止,以下代码片段尚未生效:
export default function Bye() {
const { data } = useLoaderData<typeof loader>();
return (
<div>
<h1>Off you go</h1>
<p>Some Data: {data}</p>
</div>
);
}
我对Remix不太熟悉,但我会感激任何帮助,因为我不能使用会话,因为我已经将其销毁,并且希望通过重定向发送数据。谢谢。
英文:
I have a page that logs the user out and redirects them to another page but my intention is to send some data along the redirection with redirect. I am not sure of the correct way.
in component one. I have this code
Component 1.
export const loader = async ({ request }: LoaderArgs) => {
const session = await getSession(request);
if(condition === true){
return redirect("/bye", {
headers: {
"Set-Cookie": await sessionStorage.destroySession(session),
'X-Custom-Header': 'Custom Value',
},
data: {
reason: 'we logged you out because of xyz'
}
});
}
return json({});
};
The redirection works okay. However, I need to get this data on the /bye page.
The snippet below has not worked so far:
export default function Bye() {
const { data } = useLoaderData<typeof loader>();
return (
<div>
<h1>Off you go</h1>
<p>Some Data: {data}</p>
</div>
);
}
I am not familiar with Remix yet but any help would be appreciated, I cant use a session because I killed it and was counting on sending the data via redirect.
Thanks
答案1
得分: 0
抱歉,你不能在重定向请求的主体中发送数据。这就是HTTP标准的工作原理。你可以将它作为搜索参数包含进去。
不过,你也可以使用会话 flash
,它专门设计用于此目的。它允许你在一个请求中设置一个值(如消息),然后在下一个请求中检索它。Remix会自动将其移除。
你可以在这里阅读更多信息:https://remix.run/docs/en/1.18.1/utils/sessions#sessionflashkey-value
英文:
Unfortunately, you can't send data in the body of a redirect request. That's just how the HTTP standard works. You could always include it as a search param.
However, you can also use session flash
that is designed for this purpose. It allows you to set a value (like a message) in one request and retrieve it on the very next request. Remix will then automatically remove it.
You can read about it here: https://remix.run/docs/en/1.18.1/utils/sessions#sessionflashkey-value
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论