javascript - I18N 在 Next.JS 中更改语言

标签 javascript reactjs internationalization next.js i18next

我在使用 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",
    },
}))

关于javascript - I18N 在 Next.JS 中更改语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64848259/

相关文章:

grails - 如何将默认语言设置为英语

javascript - 无法在 Node Express 应用程序中放置错误

javascript - React HashRouter不渲染其他路径,仅渲染根组件 '/'

javascript - Express:在子路由上提供 Webpack 包

windows - 'Language neutral' 对于 MAKELANGID 意味着什么?

GWT i18n - 复数形式根本不起作用?

c# - Asp.Net 中的 Flesch-Kincaid 可读性

javascript - 一旦在不同容器中达到最大长度,就聚焦下一个输入

javascript - Express next() 中间件不会触发 .catch() block 中的下一个中间件

javascript - TypeScript 编译错误