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

标签 reactjs redux internationalization next.js react-intl

我正在从 迁移项目next.js 7 到 10。它使用 react 国际用于翻译,是用 TypeScript 编写的。

在之前的版本中我 有一个自定义的 server.js 和处理 子路由 (/de、/fr 等)用于多语言用途 在里面 .在自定义应用程序组件中,通过 getInitialProps,我得到了 语言环境 来自 请求 并将其作为 Prop 传递给我的组件。所以整个画面是这样的:

自定义应用程序:

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!)
提前致谢

最佳答案

您可以访问 locale在您的自定义应用程序的 getInitialProps 中通过 router支柱。

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 .

关于reactjs - Next.js 10 + 子路由,如何在服务器端的自定义应用程序中访问语言环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65436443/

相关文章:

javascript - 如何在 React 和 Typescript 中使用 useRef 钩子(Hook)和 getClientBoundingRect?

css - React-Select 移除焦点边框

javascript - 使用 redux 时应该优先选择哪种生命周期方法?

ruby-on-rails - 是否可以将 globalize3 添加到外部 ActiveRecord 模型类?

php - 如何使 PoEdit 正确解析自定义 "ngettext"实现?

PHP Gettext 问题(比如非线程安全?)

html - Mac OSX 上的 Electron 应用程序,用于文件选择的输入

javascript - 如何使用上下文在 React 中的类和功能组件之间共享状态?

javascript - 状态正在更新到组件,但 props 未定义

javascript - React-router多个组件在auth情况下onEnter?