react-i18next:: 您需要使用 initReactI18next 传入 i18next 实例
我最近添加了该包并收到此错误。据我所知,我已遵循所有步骤。
我将 Next.js 与
next-i18next
包一起使用,该包通常会自动初始化。
next-i18next
文档:
然后我们在页面级组件中将
添加到serverSideTranslation
或getStaticProps
(取决于您的情况)。getServerSideProps
serverSideTranslation
添加到需要翻译的页面。
例如在您的
pages/d/[tab]/index
文件中:
import Head from 'next/head';
import { Input } from '../../../components/Input';
import YouTube from '../../../components/youtube/Main';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
const index = () => {
return (
<>
<Head>
<title>YouTube</title>
</Head>
<YouTube />
</>
);
};
export const getServerSideProps = async ({ locale }) => ({
props: {
...(await serverSideTranslations(locale, ['common']))
}
});
export default index;
然后在
Main
组件中,您可以使用以下方式访问 documentation
翻译:
t('pages.documentation')
就我而言,问题是由 VSC 导入建议造成的一个愚蠢的拼写错误,首先是我的粗心。
所以代替:
import { useTranslation } from "next-i18next";
...导入声明是:
import { useTranslation } from "react-i18next";
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'de', 'fr'],
},
react: { useSuspense: false },//this line
};
尽管这不是问题的根本原因,但可能会显示此错误消息。
我收到以下构建错误消息:
react-i18next:: You will need to pass in an i18next instance by using initReactI18next
TypeError: Cannot read properties of undefined (reading 'split')
at LanguageSwitcherLink ...
这里的根本原因是 TypeError。
就我而言,发生 TypeError 是因为我在
pages
目录中有带有参数的组件。因此,在 next build
期间,尝试将这些组件构建为静态页面。失败是因为缺少预期的参数,这就是它们未定义的原因。
我的解决方案:将组件移到
pages
文件夹之外。
之后,也不再有关于initReactI18next
的错误消息。
试试这个: 在你的 next-i18next.config.js 中:
const path = require('path')
module.exports = {
i18n: {
defaultLocale: 'fr',
locales: ['en', 'fr'],
localePath: path.resolve('./public/locales')
},
};
并在您的 _app.js 中尝试将配置文件作为第二个参数传递,如下所示:
import { appWithTranslation } from 'next-i18next'
import nextI18NextConfig from '../../next-i18next.config'
....
export default appWithTranslation(MyApp, nextI18NextConfig);
我也遇到这个问题了
但是我在 getStaticProps 中有“重新验证”属性。当我删除它时,错误就消失了。
附注也许这会对某人有帮助