Feat: Dynamic Page Route

动态路由页面 + 404 异常捕获
This commit is contained in:
2023-12-01 23:01:44 +08:00
parent 9391a37b21
commit 9482b2ac18
6 changed files with 154 additions and 3 deletions
+39
View File
@@ -0,0 +1,39 @@
import { LoaderFunctionArgs, MetaFunction, json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import Article from "~/components/common/article";
import { siteTitle } from "~/utils";
export const meta: MetaFunction<typeof loader> = ({ data }) => {
return [
{ title: data ? siteTitle(data.data.title) : "404" },
{ name: "description", content: data?.data.desc },
];
}
export async function loader({ params }: LoaderFunctionArgs) {
const slug = params["*"];
const page = await fetch(`https://paul.ren/api/page/get?slug=${slug}&html`).then((res) => res.json()) as API.Response<API.Page.IPageData>;
if (page.status === "Failed") {
throw json("Not Found", { status: 404, statusText: page.msg });
}
return json(page);
}
export default function DynamicPage() {
const page = useLoaderData<typeof loader>();
return (
<main className="px-2 py-24 max-w-3xl mx-auto">
<section className="mb-12">
<h1 className="text-center text-5xl/tight md:text-7xl/tight mb-4">{page.data.title}</h1>
<p className="text-center opacity-60">{page.data.desc}</p>
</section>
<section className="p-5 bg-white rounded-xl border-b-4 border-b-cyan-200">
<Article html={page.data.content} />
</section>
</main>
);
};
+2 -2
View File
@@ -12,13 +12,13 @@ export const meta: MetaFunction<typeof loader> = ({ data }) => {
export async function loader({ params }: LoaderFunctionArgs) {
if (Number.isNaN(Number(params.year)) || Number.isNaN(Number(params.id))) {
throw json("Not Found", { status: 404 });
throw json("Not Found", { status: 404, statusText: "链接格式错误" });
}
const note = await fetch(`https://paul.ren/api/note/get?id=${params.id}&year=${params.year}`).then((res) => res.json()) as API.Response<API.Note.INoteData>;
if (note.status === "Failed") {
throw json("Not Found", { status: 404 });
throw json("Not Found", { status: 404, statusText: note.msg });
}
return json(note);