Re-*_*lo 10 javascript ecmascript-6 reactjs next.js next.js13
您好,我正在努力找出如何在 Nextjs 13 中使用服务器操作成功进行数据突变后调用 toast。toast 是一个客户端组件,因为它使用钩子/上下文。
我该怎么做呢?
小智 2
简短的回答,没有规范的方法可以做到这一点。有解决方法。尽管它们可能相关,但根据您渲染的是服务器还是客户端组件,它们可能会有所不同。
老实说,next 没有提供开箱即用的解决方案,让用户想出他们能想到的任何解决方案,包括可能的糟糕解决方案,这很糟糕。
请参阅 cookie 示例:
// Server action file
"use server";
import { cookies } from "next/headers";
...
// At the end of your server action function:
cookies()
.set(
"my-app-toast-msg",
JSON.stringify({error: true, msg: "wrong credentials"}, {
expires: new Date(Date.now() + 10 * 1000), // 10 seconds
})
);
Run Code Online (Sandbox Code Playgroud)
// At your server component file
import { cookies } from "next/headers";
export async function Page() {
const toastMsg = cookies().get("my-app-toast-msg");
return (
<>
{!!toastMsg &&
JSON.parse(toastMsg).error &&
<ClientErrorToast errorMsg={JSON.parse(toastMsg).msg} />
...
</>
)
}
Run Code Online (Sandbox Code Playgroud)
这是一个快速的、肮脏的、未经测试的内存实现,我不知道这是否是一个好的解决方案。我使用一个错误作为例子,但你应该能够明白这个想法。
| 归档时间: |
|
| 查看次数: |
3378 次 |
| 最近记录: |