【问题标题】:ID is gone when I refresh a NextJS Dynamic Route page当我刷新 NextJS 动态路由页面时,ID 消失了
【发布时间】:2021-04-27 18:33:49
【问题描述】:

我正在尝试使动态路由正常工作,以便使用 url 中的 id 显示和检索正确的信息。这在我访问页面时有效,但是当我重新加载页面时,id 为空白。这是可以修复的吗?我在互联网上找不到答案。

任何帮助将不胜感激。

参考代码

//Initializing router
const router = useRouter();

//Getting id from url
const { id } = router.query;

//Fetching postdata
  const getPostData = async () => {
    setLoading(true);
    await db
      .collection("Posts")
      .doc(id)
      .get()
      .then(function (doc) {
        if (doc.exists) {
          setPostData(doc.data());
          setLoading(false);
        } else {
          //router.push("/404");
        }
      })
      .catch(function (error) {
        //router.push("/404");
      });
  };

【问题讨论】:

  • 你能分享一下代码,看看有什么问题吗?
  • @MihaiMoraru,是的,对不起。我编辑了帖子。
  • 强烈建议使用getServerSideProps并在定义组件的文件中导出。

标签: reactjs next.js


【解决方案1】:

这是关于 Next.js 路由的一个已知警告,您可以阅读它here

不管怎样,在你使用 router.query 的页面上添加这个:

export async function getServerSideProps(context) {
    return {
        props: {},
    };
}

【讨论】:

  • 谢谢,我在 Firebase 上托管我的网站。这还能用吗?
  • 是的,不管你在哪里托管,都一样。
  • 如果你不运行 next.js 并开启服务器端渲染,我认为这不会起作用。
  • 如果你没有在开启 SSR 的情况下运行 next.js,你可能一开始就没有问题
  • 你能看看这个相关的问题stackoverflow.com/questions/70211088/…
猜你喜欢
  • 2021-12-08
  • 1970-01-01
  • 2022-12-05
  • 2020-09-01
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 2020-04-06
  • 2017-11-27
相关资源
最近更新 更多