我在我的应用程序上使用next-i18next有问题。我确实根据需要实现了一切,但我的布局总是在实现getStaticProps的页面上重新渲染,我应该防止这种情况。
所以我创建了一个名为withStaticTranslations的文件。ts,我在页面上使用它,但当我试图在_app中加载它时。tsx或布局,它不工作。文件如下:import { GetStaticProps, GetStaticPropsContext, GetStaticPropsResult } from 'next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
type WithStaticTranslationsOptions = {
namespaces?: string[];
};
export const withStaticTranslations = (
getStaticPropsFunc?: GetStaticProps,
{ namespaces = ['common'] }: WithStaticTranslationsOptions = {}
): GetStaticProps => {
return async (context: GetStaticPropsContext): Promise<GetStaticPropsResult<any>> => {
const translations = await serverSideTranslations(context.locale || 'en', namespaces);
if (getStaticPropsFunc) {
const pageStaticProps = await getStaticPropsFunc(context);
if ('props' in pageStaticProps) {
return {
props: {
...translations,
...pageStaticProps.props,
},
};
}
return pageStaticProps;
}
return { props: translations };
};
};
我在页面上使用它的例子:
import type { NextPage } from 'next'
import React from "react";
import ImageSlider from "@/components/Organisms/ImageSlider";
import { withStaticTranslations } from '@/composables/withStaticTranslations';
import { GetStaticProps } from 'next';
const Home: NextPage = () => {
return (
<>
<ImageSlider />
</>
)
}
export const getStaticProps: GetStaticProps = withStaticTranslations();
export default Home;
那么,防止布局重新加载的最好方法是什么呢?即使我在_app中实现了所有的翻译。tsx,我认为它会导致性能问题,但即使导致性能问题,我仍然必须防止它。什么好主意吗?防止布局重新加载的一种方法是使用next-i18next
提供的useTranslation
钩子,而不是在withStaticTranslations
HOC中使用serverSideTranslations
函数。
下面是一个如何修改withStaticTranslations函数以使用useTranslation钩子的示例:
import { GetStaticProps, GetStaticPropsContext, GetStaticPropsResult } from 'next';
import { useTranslation } from 'next-i18next';
type WithStaticTranslationsOptions = {
namespaces?: string[];
};
export const withStaticTranslations = (
getStaticPropsFunc?: GetStaticProps,
{ namespaces = ['common'] }: WithStaticTranslationsOptions = {}
): GetStaticProps => {
return async (context: GetStaticPropsContext): Promise<GetStaticPropsResult<any>> => {
const { i18n } = useTranslation(namespaces);
const translations = await i18n.getInitialProps(context.locale || 'en', namespaces);
if (getStaticPropsFunc) {
const pageStaticProps = await getStaticPropsFunc(context);
if ('props' in pageStaticProps) {
return {
props: {
...translations,
...pageStaticProps.props,
},
};
}
return pageStaticProps;
}
return { props: translations };
};
};
然后,您可以在您的页面上使用withStaticTranslations
HOC:
import type { NextPage } from 'next'
import React from "react";
import ImageSlider from "@/components/Organisms/ImageSlider";
import { withStaticTranslations } from '@/composables/withStaticTranslations';
import { GetStaticProps } from 'next';
const Home: NextPage = () => {
return (
<>
<ImageSlider />
</>
)
}
export const getStaticProps: GetStaticProps = withStaticTranslations();
export default Home;
通过使用useTranslation钩子,翻译将被缓存在客户端,并且布局不需要在每次访问页面时重新加载。