Explorar el Código

fix: 尝试修复多语言bug

F-DEV hace 9 horas
padre
commit
8aaa223bd3
Se han modificado 3 ficheros con 20 adiciones y 16 borrados
  1. 2 2
      src/components/LanguageSwitch.tsx
  2. 6 3
      src/i18n/index.ts
  3. 12 11
      src/main.tsx

+ 2 - 2
src/components/LanguageSwitch.tsx

@@ -3,8 +3,8 @@ import { useTranslation } from 'react-i18next';
 
 const LANGUAGES = [
     { code: 'en-US', label: 'English' },
-    // { code: 'zh-CN', label: '简体中文' },
-    // { code: 'fa-IR', label: 'فارسی' },
+    { code: 'zh-CN', label: '简体中文' },
+    { code: 'fa-IR', label: 'فارسی' },
 ];
 
 interface LanguageSwitchProps {

+ 6 - 3
src/i18n/index.ts

@@ -121,6 +121,7 @@ i18n.use(LanguageDetector)
 // ****************** 使用 LanguageDetector、支持按需加载翻译文件 时 i18n 的配置方法 ******************
 // 临时只启用英文,恢复多语言时把数组清空或删掉过滤逻辑
 const ENABLED_LANGS = ['en-US'];
+// const ENABLED_LANGS: string[] = [];
 
 // 匹配 locales 下所有 .ts,显式排除 dirMap.ts(fast-glob 否定语法)
 const modules = import.meta.glob(['@/locales/*.ts', '!@/locales/dirMap.ts']);
@@ -166,8 +167,9 @@ i18n.on('languageChanged', async (lang) => {
     }
 });
 
-// 初始化i18n
-i18n.use(LanguageDetector)
+// 初始化i18n,并在初始语言的翻译文件加载完成后 resolve,供 main.tsx 等待后再挂载 React
+export const i18nReady = i18n
+    .use(LanguageDetector)
     .use(initReactI18next)
     .init({
         supportedLngs: supportedLanguages,
@@ -191,7 +193,8 @@ i18n.use(LanguageDetector)
             suffix: '}',
         },
         resources: {},
-    });
+    })
+    .then(() => loadLanguage(i18n.language));
 // ****************** 使用 LanguageDetector、支持按需加载翻译文件 时 i18n 的配置方法 end ******************
 
 export default i18n;

+ 12 - 11
src/main.tsx

@@ -5,13 +5,12 @@ import utc from 'dayjs/plugin/utc';
 import ReactDOM from 'react-dom/client';
 import { I18nextProvider } from 'react-i18next';
 
-import './i18n';
 import './styles/antd.scss';
 import './styles/global.scss';
 import './styles/tailwind.css';
 
 import App from './App';
-import i18n from './i18n';
+import i18n, { i18nReady } from './i18n';
 
 // 配置 dayjs
 dayjs.extend(utc);
@@ -57,13 +56,15 @@ const initDocumentDirection = (language: string) => {
     document.documentElement.lang = language;
 };
 
-// 初始化时设置方向
-initDocumentDirection(i18n.language);
+// 等初始语言翻译文件加载完成后再挂载,避免刷新时因缓存加速导致翻译未就绪就渲染
+i18nReady.then(() => {
+    initDocumentDirection(i18n.language);
 
-ReactDOM.createRoot(document.getElementById('root')!).render(
-    <React.StrictMode>
-        <I18nextProvider i18n={i18n}>
-            <App />
-        </I18nextProvider>
-    </React.StrictMode>
-);
+    ReactDOM.createRoot(document.getElementById('root')!).render(
+        <React.StrictMode>
+            <I18nextProvider i18n={i18n}>
+                <App />
+            </I18nextProvider>
+        </React.StrictMode>
+    );
+});