Next.js 10 + 子路由,如何在服务器端的自定义应用程序中访问语言环境

Ali*_*sah 5 internationalization reactjs redux react-intl next.js

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

在以前的版本我有一个自定义的server.js和处理子路由多语言的目的(/日,/ FR等),在它。在自定义应用程序组件中,通过 getInitialProps,我从req获取语言环境并将其作为道具传递给我的组件。所以整个画面是这样的: 自定义应用程序:

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 }
}
Run Code Online (Sandbox Code Playgroud)

和组件

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

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

module.exports = {
   i18n: {
        locales: ["en", "de", "fr"],
        defaultLocale: "en",
    },
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

提前致谢

jul*_*ves 5

您可以通过prop访问locale自定义应用程序中的。getInitialPropsrouter

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 }
}
Run Code Online (Sandbox Code Playgroud)

在自定义应用程序页面之外使用getServerSideProps/ 时getStaticProps,可以直接从上下文对象访问活动语言环境。

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 }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看Next.js i18n 路由文档