nextjs动态路由与next-i18next不兼容。

huangapple go评论116阅读模式
英文:

nextjs dynamic routes doesn't work with next-i18next

问题

我刚刚在我的Next.js项目中按照官方指南添加了next-i18next,一切似乎都很正常,但当我将语言从默认语言(意大利语)更改为英语并且访问一个实体的详细信息时,我会得到404错误。这仅在动态路由和非默认语言下发生。

我将向您展示更多细节。

我的next-i18next.config.js文件:

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

[id].tsx

//我的NextPage组件...

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 = {
    //...
  };

  //这一行不是问题,即使我删除它,问题仍然存在。我确信项目存在。
  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.,但我认为我根据这篇文档已经做得正确。正如我之前所说,如果我尝试在将语言更改为“en”后访问动态路由,则会进入404页面。

您有什么建议来解决这个问题?

英文:

I just added next-i18next in my nextjs project following the official guide and everything seemed to be in order, but when I change the language from default (Italian) to English and I go to the detail of an entity then I get 404. This happens only with the dynamic routes and only with the language that is not the default one.

I am going to show you more details.

My next-i18next.config.js file:

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

[id].tsx

//My NextPage component...

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

  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, [
        &quot;common&quot;,
        &quot;footer&quot;,
        &quot;projects&quot;,
      ])),
      seo,
      project,
    },
  };
}

index.tsx (under projects folder)

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

Also I get the error Error: The provided &#39;href&#39; (/projects/[slug]) value is missing query values (slug) to be interpolated properly. when I try to change the language while I am in the detail of the project with the italian language set, but I think I did it right according to this doc. As I said before, instead, if I try to go into the dynamic route after having changed the language to "en" then I go to 404 page.

Do you have any suggestions to solve this problem?

答案1

得分: 1

我通过更新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,
  };
}

所以必须将区域传递到路径中。

英文:

I solved this by updating the mothod getStaticPaths to:

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

  return {
    paths,
    fallback: true,
  };
}

So there must be passed the locale into the paths.

huangapple
  • 本文由 发表于 2023年2月18日 20:46:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定