nextjs动态路由不与next-i18 next一起工作

wvt8vs2t  于 2023-02-22  发布在  其他
关注(0)|答案(1)|浏览(137)

我刚刚在official guide之后在我的nextjs项目中添加了next-i18 next,一切看起来都很正常,但是当我将语言从默认(意大利语)更改为英语并转到实体的详细信息时,我得到了404。这种情况仅发生在动态路由和非默认语言的情况下。
我将向您展示更多细节。
我的next-i18next.config.js文件:

module.exports = {
  i18n: {
    defaultLocale: "it",
    locales: ["it", "en"],
  },
};

[id].tsx

//My NextPage component...

export async function getStaticPaths() {
  const paths = await projects.find()?.map((_project) => ({
    params: { id: _project.id + "" },
  }));

  return {
    paths,
    fallback: false,
  };
}

export async function getStaticProps({
  locale,
  ...rest
}: {
  locale: string;
  params: { id: string };
}) {
  const project = await projects.findOne({id: rest.params.id})

  const seo: Seo = {
    //...
  };
  
  //This row is not the problem, since it persists even if I remove it. Also I am sure that the project exists.
  if (!project?.id) return { notFound: true };

  return {
    props: {
      ...(await serverSideTranslations(locale, [
        "common",
        "footer",
        "projects",
      ])),
      seo,
      project,
    },
  };
}

index.tsx(在项目文件夹下)

const Projects: NextPage<Props> = ({ /*...*/ }) => {
  //...
  const router = useRouter();
  
  return <button onClick={() =>
          router.push({
            pathname: `/projects/[slug]`,
            query: { slug: project.slug },
          })
        }>Read more</button>
}

当我尝试改变语言时,我也得到了错误Error: The provided 'href' (/projects/[slug]) value is missing query values (slug) to be interpolated properly.,而我在项目的细节与意大利语设置,但我认为我这样做是正确的,根据this doc.正如我之前所说,相反,如果我试图进入动态路线后,改变语言为“en”,然后我去404页.
你对解决这个问题有什么建议吗?

ilmyapht

ilmyapht1#

我通过将方法getStaticPaths更新为以下内容解决了这个问题:

export async function getStaticPaths({ locales }: { locales: string[] }) {
  const projects = getProjects({ locale: "it" });
  const paths = projects.flatMap((_project) => {
    return locales.map((locale) => {
      return {
        params: {
          type: _project.slug,
          slug: _project.slug,
        },
        locale: locale,
      };
    });
  });

  return {
    paths,
    fallback: true,
  };
}

因此必须将区域设置传递到路径中。

相关问题