【问题标题】:Next.js dynamic routes with Firestore collection带有 Firestore 集合的 Next.js 动态路由
【发布时间】:2021-11-02 12:54:13
【问题描述】:

我正在寻找一种使用服务器端渲染为 Firestore 集合中的每个文档显示动态路由的方法。

例如,名为foo 的文档将存在于test.com/foo[doc] 页面组件下。任何时候添加一个文档,都应该能够通过其各自的 URL 访问它。

我已经尝试过this 方法,但我无法让它工作。 我也尝试过实现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;

【问题讨论】:

  • 该链接中的方法有什么错误或其他什么不起作用??
  • 控制台登录时name变量未定义,fetcher函数中返回res.json()为空
  • 在这种情况下,您应该共享该函数的minimal, reproducible example,以便我们查看它有什么问题。
  • 添加到我的问题中!
  • 你能尝试像gist那样使用getServerSideProps吗?

标签: javascript firebase google-cloud-firestore ecmascript-6 next.js


【解决方案1】:

你可以试试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;

【讨论】:

    【解决方案2】:

    简单的解决方案。

    const { data } = useSWR(api ? '/api/${name}' : null, fetcher);
    

    如果定义了变量,则有条件地获取数据,如果没有,最好不要传递 URL 字符串;您也可以有条件地考虑使用 fetcher。

    const { data } = useSWR(name ? '/api/${name}' : null, name ? fetcher : null);
    

    【讨论】:

      猜你喜欢
      • 2020-09-08
      • 2021-12-03
      • 2022-11-05
      • 2021-11-18
      • 2022-01-10
      • 2022-01-04
      • 2021-12-17
      • 2021-01-29
      • 1970-01-01
      相关资源
      最近更新 更多