Reactjs Next.js 10+;子路由,如何访问服务器端自定义应用程序中的区域设置

Reactjs Next.js 10+;子路由,如何访问服务器端自定义应用程序中的区域设置,reactjs,redux,internationalization,next.js,react-intl,Reactjs,Redux,Internationalization,Next.js,React Intl,我正在将一个项目从next.js7迁移到10。它使用react intl进行翻译,并使用打字脚本编写。 在以前的版本中,I有一个自定义的server.js,并处理子路由(/de、/fr等),用于多语言目的。在自定义应用程序组件中,通过getInitialProps,我从req获取locale,并将其作为道具传递给我的组件。所以整个画面是这样的: 自定义应用程序: static async getInitialProps({ Component, ctx }) { let pageP

我正在将一个项目从next.js7迁移到10。它使用react intl进行翻译,并使用打字脚本编写。

在以前的版本中,I有一个自定义的server.js,并处理子路由(/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>
        )
    }
唯一的问题是,我需要在服务器端和所有页面中将区域设置传递给react intl的IntlProvider。所以我想我应该在自定义应用程序中这样做,getInitialProps为locale返回一个错误的值(总是默认值)。我们不能在自定义应用程序中使用getServerSideProps或getStaticProps

最后!问题是: 如何在一个位置访问服务器端上所有页面的区域设置?还是有更好的方法来解决这个问题

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


提前感谢

您可以通过
路由器
道具访问自定义应用程序
获取初始道具
中的
区域设置

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
时,可以直接从上下文对象访问活动区域设置

导出异步函数getServerSideProps({locale}){
console.log(locale)//记录当前区域设置
// ...
}


有关更多详细信息,请检查。

您好,只想询问您删除自定义服务器的原因是因为下一个国际化路由不支持自定义服务器@Ali AfsahHi@more,我删除了自定义服务器,因为我想在Vercel上部署我的应用程序,而且它会造成一些性能问题。根据Next.js 10文档,建议不要使用它,除非默认路由系统不足以满足您的特定任务。请看一下这份官方文件的前几行:
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 }
}