我正在将一个项目从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 }
}
和组件
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 }
}
您可以查看i18n路由文档以了解更多详细信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句