next-i18next在vercel上部署后不能在动态页面中使用serversideprops &



我使用next-i18next模块来支持多语言。

我也有一些静态页面和动态页面。

我在vercel上部署了所有静态页面,在vercel上都工作得很好。但是动态页面不能在vercel上工作。它显示了该动态页面的404页面。

动态页面代码如下:(页面/测试页面/[questionId] . js)

import { useState, useEffect } from "react";
import {Layout} from "@components/common";
import { useRouter } from 'next/router';
import { useTranslation } from 'next-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import { TestComponent } from '@components/TestComponent'
const TestPage = () => 
{
const { t } = useTranslation('common')
const router = useRouter()
const {questionId} = router.query;
const [isApiLoaded,setIsApiLoaded] = useState(false)

return (
<TestComponent 
t={t}
isApiLoaded={isApiLoaded}
setIsApiLoaded={setIsApiLoaded}
/>
)
}
TestPage.Layout = Layout
export const getServerSideProps = async ({ locale }) => ({
props: {
...(await serverSideTranslations(locale, ['home', 'common']))
}
});
export default TestPage;

如何解决这个问题?

在next-i18next.config.js中添加localePath确实对我的情况有所帮助。

const path = require('path')
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'de'],
localePath: path.resolve('./public/locales')
}
};

我面临着同样的问题,为了临时修复,我使用了来自next-i18nexti18n对象,该对象具有一个名为getResource的函数,该函数通过其翻译获取当前语言环境

// import { i18n } from 'next-i18next';
// import { useRouter } from 'next/router';
const [translation, setTranslation] = useState({});
useEffect(() => {
const bundle = i18n.getResource(locale, 'common');
setTranslation(bundle);
}, []);
为了避免用t函数重写代码,您可以使用
// LINK https://stackoverflow.com/a/43849204/14263138
const t = (word) => word
.split('.')
.reduce((p, c) => (p && p[c]) || null, translation);

应用此功能后,您不需要使用getServerSideProps

虽然这篇文章已经过时了,但我还是分享了我在项目中解决这个问题的方法(重点是添加localePath):

const path = require('path');
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'it', 'de', 'es', 'fr', 'ja']
},
defaultNs: 'shared',
fallbackLng: { default: ['en', 'it', 'de', 'es', 'fr', 'ja'] },
localePath: path.resolve('./public/locales'),
};

我指定localePath不应该包含在i18n的属性中,因为这样做会产生类型错误。

确保在页面上使用getServerSideProps而不是getStaticProps,例如:

export async function getServerSideProps({ locale }) {
return {
props: {
...(await ssrTranslations(locale, ['login', 'shared'])),
},
};
}

导入serverSideTranslations

import { serverSideTranslations } from "next-i18next/serverSideTranslations";

现在从getServerSideProps中传递…(await serverSideTranslations(locale, ["common"]))),与props。

export const getServerSideProps: GetStaticProps = async ({
locale,
locales,
query
}: any) => {
return {
props: {
...(await serverSideTranslations(locale, ["common"])),
}
}
};

现在在里面添加你的语言字符串/公共/地区/en/common.json

例如

{
"home": {
"Test": "Test"
}
}

您可以在locale目录中添加更多的语言字符串。

重启你的Next.js应用,它会工作的。