【问题标题】:How to access locale in custom app on server-side in Next.js?Next.js 10 + 子路由,如何在服务器端的自定义应用程序中访问语言环境
【发布时间】:2021-04-02 19:04:27
【问题描述】:

我正在将一个项目从 next.js 7 迁移到 10。它使用 react-intl 进行翻译,并且是用 TypeScript 编写的。

在之前的版本中,我有一个自定义 server.js 并处理 sub-routing(/de、/fr 等)用于多语言目的在其中强>。在自定义应用程序组件中,通过 getInitialProps,我从 req 获取 locale 并将其作为道具传递给我的组件。所以整个画面是这样的:
自定义应用:

static async getInitialProps({ Component, ctx }) {
    let pageProps = {}

    const { req } = ctx;
    const { locale, messages } = req || (window as any).__NEXT_DATA__.props;
    const initialNow = Date.now();

    if (Component.getInitialProps) {
        pageProps = await Component.getInitialProps(ctx)
    }
    return { pageProps, locale, messages, initialNow }
}

还有组件

render() {
        const { Component, pageProps, locale, messages, initialNow } = (this.props as any);
        return (
            <Container>
                <IntlProvider locale={locale} messages={messages} initialNow={initialNow}>
                    <Component {...pageProps} />
                </IntlProvider>
            </Container>
        )
    }

现在由于我使用的是 next.js 10,出于多种原因,我删除了自定义 server.js 并通过 i18n 进行了子路由,所以我在 next.config.js 中添加了这个:

module.exports = {
   i18n: {
        locales: ["en", "de", "fr"],
        defaultLocale: "en",
    },
}

唯一的事情是我需要将语言环境传递给服务器端和所有页面的 react-intl 的 IntlProvider。所以我想我应该在自定义应用程序中执行此操作,并且 getInitialProps 为语言环境返回错误值(始终默认)。而且我们不能在自定义 _app 中使用 getServerSideProps 或 getStaticProps。

最后!问题是: 如何在一个地方为我的所有页面访问服务器端的语言环境?或者有没有更好的方法来解决这个问题?

(我现在无法删除 intl 并完全使用 i18n,这个特定项目需要很多时间,而我们没有 atm!)

提前致谢

【问题讨论】:

  • 嗨,只是想问一下您删除自定义服务器的原因是因为下一个国际化路由不支持自定义服务器? @Ali Afsah
  • 嗨@Anymore,我删除了自定义服务器,因为我想在 Vercel 上部署我的应用程序,而且它产生了一些性能问题。基于 Next.js 10 文档,建议不要使用它,除非默认路由系统不足以满足您的特定任务。请看一下这个官方文档的前几行:nextjs.org/docs/advanced-features/custom-server

标签: reactjs redux internationalization next.js react-intl


【解决方案1】:

您可以通过router 属性访问自定义应用的getInitialProps 中的locale

static async getInitialProps({ Component, ctx, router }) {
    let pageProps = {}

    const { req } = ctx;
    const { locale } = router; // Will return `fr` for `/fr/*` pages
    const { messages } = req || (window as any).__NEXT_DATA__.props;
    const initialNow = Date.now();

    if (Component.getInitialProps) {
        pageProps = await Component.getInitialProps(ctx)
    }
    return { pageProps, locale, messages, initialNow }
}

在自定义应用页面之外使用getServerSideProps/getStaticProps 时,可以直接从上下文对象访问活动区域设置。

export async function getServerSideProps({ locale }) {
    console.log(locale) // Logs current locale    

    // ...
}

更多详情请查看Next.js i18n routing documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    相关资源
    最近更新 更多