Remix Toast 使用教程
项目介绍
Remix Toast 是一个用于在 Remix 应用中实现服务器端 toast 通知的简单管理库。它提供了所有必要的工具,以便向用户显示 toast 通知。客户端实现完全由开发者决定,可以使用任何库来显示 toast。服务器端使用 @remix-run/server-runtime 原语创建 cookie 会话,因此该库与服务器无关,应该适用于任何服务器设置。
项目快速启动
安装
首先,通过 npm 安装 Remix Toast:
npm install remix-toast
设置服务器端
在根 tsx
文件中添加以下代码:
import { getToast } from "remix-toast";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { useEffect } from "react";
export const loader = async ({ request }: LoaderFunctionArgs) => {
// 从请求中提取 toast
const { toast, headers } = await getToast(request);
// 重要:传递 headers 以便正确清除 toast
return json({ toast }, { headers });
};
export default function App({ children }: { children: ReactNode }) {
const { toast } = useLoaderData<typeof loader>();
useEffect(() => {
if (toast) {
// 在这里调用你的 toast 函数
alert(toast.message);
}
}, [toast]);
return <>{children}</>;
}
应用案例和最佳实践
在表单提交时显示 toast 通知
以下是一个示例,展示如何在表单提交成功后显示 toast 通知:
import { redirectWithToast } from "remix-toast";
export const action = () => {
return redirectWithToast("/login", {
message: "You need to login to access this page",
description: "description of toast",
type: "error",
});
};
显示成功 toast 消息
以下是一个示例,展示如何在不需要重定向的情况下显示成功 toast 消息:
import { jsonWithSuccess } from "remix-toast";
export const action = () => {
return jsonWithSuccess({ result: "Data saved successfully" }, "Operation successful 🎉");
};
典型生态项目
Sonner
Sonner 是一个流行的 toast 通知库,可以与 Remix Toast 结合使用。以下是如何在 Remix 应用中使用 Sonner 显示 toast 通知的示例:
import { json, type LinksFunction, type LoaderFunctionArgs } from "@remix-run/node";
import { Links, LiveReload, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData } from "@remix-run/react";
import { useEffect } from "react";
import { getToast } from "remix-toast";
import { Toaster, toast as notify } from "sonner";
export const loader = async ({ request }: LoaderFunctionArgs) => {
const { toast, headers } = await getToast(request);
return json({ toast }, { headers });
};
export default function App() {
const { toast } = useLoaderData<typeof loader>();
useEffect(() => {
if (toast) {
notify(toast.message, { type: toast.type });
}
}, [toast]);
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
<Outlet />
<Scripts />
<ScrollRestoration />
<LiveReload />
<Toaster />
</body>
</html>
);
}
通过以上步骤,您可以在 Remix 应用中轻松实现和管理 toast 通知。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考