简体   繁体   English

如何处理 Next.js 中动态页面的国际化后备页面?

[英]How to handle fallback page with internationalization for dynamic page in Next.js?

In Next.js documentation, there is a section for internationalized routing with dynamic routes and getStaticProps pages .在 Next.js 文档中,有一个用于国际化路由的部分,其中包含动态路由和 getStaticProps 页面

In the provided example, they use the fallback property set to true:在提供的示例中,他们使用设置为 true 的 fallback 属性:

// pages/blog/[slug].js
export const getStaticPaths = ({ locales }) => {
  return {
    paths: [
      // if no `locale` is provided only the defaultLocale will be generated
      { params: { slug: 'post-1' }, locale: 'en-US' },
      { params: { slug: 'post-1' }, locale: 'fr' },
    ],
    fallback: true,
  }
}

I have a very similar project with 2 locales: 'en' and 'fr'.我有一个非常相似的项目,有 2 个语言环境:“en”和“fr”。 Everything is working fine when my blog article does exist.当我的博客文章确实存在时,一切正常。 But if the article does not exists (or when the page has not been generated yet at build time), then I display my custom fallback page as explained here .但是,如果文章不存在(或者在构建时尚未生成页面),那么我会按照此处的说明显示我的自定义后备页面。

I could provide my getStaticProps function or fallback page.我可以提供我的getStaticProps function 或后备页面。 But it is very similar to the example defined on the doc as well, so very simple.但它也与文档上定义的示例非常相似,非常简单。

The issue is that when displaying my fallback page, I do not have any locale yet.问题是在显示我的后备页面时,我还没有任何语言环境。 So all my translations display keys instead of english or french value (not only for my fallback custom component but the whole main layout/page).所以我所有的翻译都显示键而不是英文或法文值(不仅用于我的后备自定义组件,还用于整个主布局/页面)。

From what I understand the problem is that:据我了解,问题在于:

  1. Fallback page is displayed until getStaticProps has finishedgetStaticProps完成之前显示后备页面
  2. Fallback page props are empty后备页面道具为空
  3. Locale is returned by getStaticProps function语言环境由getStaticProps function 返回

I feel like this should be a common scenario, and maybe I'm missing something.我觉得这应该是一个常见的场景,也许我错过了一些东西。 How could I know the locale when displaying the fallback page?显示后备页面时如何知道语言环境?

Please note that I use next-i18next on my project.请注意,我在我的项目中使用 next-i18next。 So my URL is either: /articles/[slug] or /fr/articles/[slug] .所以我的 URL 是: /articles/[slug]/fr/articles/[slug]

You can access the current locale while displaying the fallback page using router.locale from next/router .您可以在使用来自next/routerrouter.locale显示回退页面时访问当前语言环境。

// pages/blog/[slug].js
import { useRouter } from 'next/router'

function Blog() {
    const router = useRouter()

    if (router.isFallback) {
        return <div>{`Loading ${router.locale} fallback page...`}</div>
    }

    return <div>Blog page</div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM