I18N在Next中更改语言,JS

eqzww0vc  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(158)

我有一些问题与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.

我用的是最新的Nextjs和I18N我发现当代码到达I18N时程序崩溃。changeLanguage('en ').如果我使用该按钮来设置新的区域设置,也会发生同样的错误。我知道下一个。js有从URL读取locale的选项,但我想从本地存储使用locale。有没有可能在下一个js中以这种方式使用I18N?我也发现,如果我控制台日志i18n它给我回来,i18n有changeLanguage功能。
谢谢大家的回应!我不知道该怎么办:)
更新:Nextconfig.js:

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

nxowjjhe1#

您可以在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",
    },
}))

相关问题