在Next.js中使用SSG进行动态路由,但仅在客户端页面上获取数据(在构建时仍然未知ID)

tzcvj98z  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(65)

我在SSG中使用Next.js,但有些数据只能由授权用户访问(实时获取)。在根层,我提供了[lang]
例如,user页面应该是基于ID的。我不想在构建时添加此页面。当然,用户模板应该使用SSG进行预渲染。在客户端,我想使用SWR来获取访问时的用户数据。
我不想用/en/user/?id=someone,我想用/en/user/someone/
我的文件夹结构看起来像这样:

[lang]
 ┣ user
 ┃ ┗ [userID]
 ┃ ┃ ┗ index.js
 ┗ index.js

字符串
这在开发时有效,但在构建后无效(如果我想访问userID 2,3,...,则为404)。

export async function getStaticPaths() {
  const paths = [
    { params: { lang: "en", userID: "1" } },
    { params: { lang: "de", userID: "1" } },
  ];

  return {
    paths,
    fallback: true,
  };
}


有办法解决吗?

djmepvbi

djmepvbi1#

解决了!
Simple在next.config.js中添加了重写:

async rewrites() {
  return [
    {
      source: "/:lang/user/:userID",
      destination: "/:lang/user?userID=:userID",
    },
  ];
},

字符串
最后添加了/lang/user.js并获得了参数:

const router = useRouter();
const { userID} = router.query;

相关问题