Next.js 错误:文本内容不匹配

问题描述 投票:0回答:1

我在 next.js 项目中使用react-i18next 进行本地化。但当我刷新页面时,我出现了这些错误。

错误

  1. 警告:文本内容不匹配。服务器:“page_about” 客户端:“关于我们”
  2. 警告:水合过程中发生错误。服务器 HTML 已替换为
    中的客户端内容。
  3. 未捕获错误:文本内容与服务器渲染的 HTML 不匹配。
  4. 未捕获的错误:补水时出现错误。因为错误发生在 Suspense 边界之外,所以整个根将切换到客户端渲染。

src/configs/i18n.js

import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'

i18n
  // Enables the i18next backend
  .use(Backend)

  // Enable automatic language detection
  .use(LanguageDetector)

  // Enables the hook initialization module
  .use(initReactI18next)
  .init({
    lng: 'tr',
    backend: {
      /* translation file path */
      loadPath: '/locales/{{lng}}.json'
    },
    fallbackLng: 'tr',
    debug: false,
    keySeparator: false,
    react: {
      useSuspense: false
    },
    interpolation: {
      escapeValue: false,
      formatSeparator: ','
    }
  })

export default i18n

_app.js

...
import 'src/configs/i18n'

const MyApp = ({ Component, pageProps }) => {

    const getLayout = Component.layout ?? (page => <Layout>{page}</Layout>)

    return (
        <>
            <Provider store={store}>
                <ThemeProvider theme={theme}>
                    {
                        getLayout(<Component {...pageProps} />)
                    }
                </ThemeProvider>
            </Provider>
        </>
    )
}

MyApp.getInitialProps = async (context) => {
    const ctx = await App.getInitialProps(context)

    return {
        ...ctx,
    };
};


export default MyApp

Translations.js

import { useTranslation } from "react-i18next";

const Translations = ({ text }) => {
  // ** Hook
  const { t } = useTranslation()

  return <>
    {`${t(text)}`}
  </>
}

export default Translations

我在组件中使用

...
<Translations text={subItem.name} />
...

我尝试使用 next-i18next、Suspense、命名空间

next.js localization i18next react-i18next
1个回答
0
投票

您必须将 serverSideTranslation 函数传递给您的组件才能使其访问翻译文件,如下所示:

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

export const getStaticProps = async ({ locale }) => ({
props: {
 ...(await serverSideTranslations(locale, [
  "common", 
 ])),
},
});
© www.soinside.com 2019 - 2024. All rights reserved.