I18N 更改 Next.JS 中的语言

I18N change language in Next.JS

我在使用 I18N 和 NextJS 时遇到了一些问题。所以我配置了我的 I18N,一切都使用默认语言环境,但如果我想从本地存储更改语言环境,一切都会崩溃。
在 _app.js 我尝试使用这个函数:

const { i18n } = useTranslation();
useEffect(() => {
    if(localStorage.getItem('Locale')) {
        i18n.changeLanguage(localStorage.getItem('Locale'))
    }
}, [])

我导入了:

import './I18N/i18next';
import { useTranslation } from 'react-i18next'

应用程序加载时崩溃并给出错误:

The above error occurred in the <MyApp> component:

at MyApp (webpack-internal:///./pages/_app.js:35:24)
at ErrorBoundary (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ErrorBoundary.js:23:47)
at ReactDevOverlay (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js:73:23)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:146:5)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:623:24)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:739:25)

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.

我使用的是最新的 Next.js 和 I18N 我发现当代码达到 i18n.changeLanguage('en') 时程序崩溃。如果我使用按钮设置新的语言环境,则会发生同样的错误。我知道 next.js 可以选择从 URL 读取语言环境,但我想使用本地存储中的语言环境。这样在下一个js中可以使用I18N吗?我也发现,如果我控制台登录 i18n,它会告诉我 i18n 具有 changeLanguage 函数。
谢谢大家的回复!我完全不知道该怎么办:(

更新: next.config.js:

const withLess = require('@zeit/next-less');
const withSass = require('@zeit/next-sass');
module.exports = withSass(withLess({
    lessLoaderOptions: {
        javascriptEnabled: true
    }
}))

您可以在 next.config.js

中更改默认本地

_app.js中你可以在路由器

中获取本地
const router = useRouter();
const { locale } = router;
const { i18n } = useTranslation();

useEffect(() => {
    i18n.changeLanguage(locale);
  }, [locale]);

我假设你有两个语言环境(fr, en)

next.config.js

const withLess = require('@zeit/next-less');
const withSass = require('@zeit/next-sass');
module.exports = withSass(withLess({
    lessLoaderOptions: {
        javascriptEnabled: true
    },
    i18n: {
        locales: ["fr", "en"],
        defaultLocale: "fr",
    },
}))