[英]Next.js dynamic routes with Firestore collection
我正在寻找一种使用服务器端渲染为 Firestore 集合中的每个文档显示动态路由的方法。
例如,名为foo
的文档将存在于test.com/foo
的[doc]
页面组件下。 任何时候添加文档时,都应该能够通过其各自的 URL 访问它。
我已经尝试过这种方法,但我无法让它发挥作用。 我也尝试过实现getServerSideProps
但没有取得太大成功,任何指针将不胜感激。
上述方法的代码如下:
在pages/api/[doc].js
下
export default (req, res) => {
db.collection("docs")
.doc(req.query.name)
.get()
.then((doc) => {
res.json(doc.data());
})
.catch((error) => {
res.json({ error });
});
};
在pages/[shoal].jsx
import { useRouter } from "next/router";
import useSWR from "swr";
const fetcher = async (...args) => {
const res = await fetch(...args);
return res.json();
};
function Doc() {
const router = useRouter();
const { name } = router.query;
const { data } = useSWR(`/api/${name}`, fetcher);
if (!data) {
return "Loading...";
}
return (
<div>
<p>Title: {data.title}</p>
</div>
);
}
export default Doc;
您可以尝试使用getServerSideProps
:
export const getServerSideProps = async (ctx) => {
const doc = await db.collection("docs").doc(ctx.query.id).get()
const data = doc.data()
if (!data) return { notFound: true };
return { props: { data } };
};
function Doc({data}) {
const router = useRouter();
const { name } = router.query;
if (!data) {
return "Loading...";
}
return (
<div>
<p>Title: {data.title}</p>
</div>
);
}
export default Doc;
简单的解决方案。
const { data } = useSWR(api ? '/api/${name}' : null, fetcher);
如果定义了变量,则有条件地获取数据,如果没有,最好不要传递 URL 字符串; 您也可以有条件地考虑使用 fetcher。
const { data } = useSWR(name ? '/api/${name}' : null, name ? fetcher : null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.