feat: auto-detect browser language (SSR Accept-Language + cookie)
- layout (server): derive language from cookie (user choice) > browser Accept-Language; set <html lang> accordingly - I18nInit → I18nProvider: sync initI18n(lng) before children render (SSR/CSR first render same language, no hydration mismatch) - setAppLanguage also writes cookie so SSR first paint uses chosen lang - Verified: en browser → lang=en, zh → zh-CN, cookie overrides
This commit is contained in:
1 parent
08302dc0d7
commit
dce94fd5af
3 files changed
+52
-27
No files matched your search
+21
-3
@@ -1,5 +1,6 @@
|
|||||||
// 全局布局
|
// 全局布局
|
||||||
import './globals.css';
|
import './globals.css';
|
||||||
|
import { cookies, headers } from 'next/headers';
|
||||||
import CustomCssLoader from '@/components/CustomCssLoader';
|
import CustomCssLoader from '@/components/CustomCssLoader';
|
||||||
import { ToastProvider } from '@/components/Toast';
|
import { ToastProvider } from '@/components/Toast';
|
||||||
import I18nInit from '@/components/I18nInit';
|
import I18nInit from '@/components/I18nInit';
|
||||||
@@ -12,9 +13,26 @@ export const metadata = {
|
|||||||
description: 'Forumlify - 简洁优雅的现代社区系统',
|
description: 'Forumlify - 简洁优雅的现代社区系统',
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({ children }) {
|
// cookies()/headers() 是动态 API:禁止静态优化
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export default async function RootLayout({ children }) {
|
||||||
|
// 语言检测:用户配置 cookie 优先,否则按浏览器 Accept-Language
|
||||||
|
let lng = 'zh';
|
||||||
|
try {
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const saved = cookieStore.get('forumlify-lang')?.value;
|
||||||
|
if (saved === 'en' || saved === 'zh') {
|
||||||
|
lng = saved;
|
||||||
|
} else {
|
||||||
|
const hdrs = await headers();
|
||||||
|
const accept = (hdrs.get('accept-language') || '').toLowerCase();
|
||||||
|
if (accept.startsWith('en')) lng = 'en';
|
||||||
|
}
|
||||||
|
} catch (e) { /* 默认 zh */ }
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html lang="zh-CN" suppressHydrationWarning>
|
<html lang={lng === 'en' ? 'en' : 'zh-CN'} suppressHydrationWarning>
|
||||||
<head>
|
<head>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -31,7 +49,7 @@ export default function RootLayout({ children }) {
|
|||||||
// React 状态渲染,SSR/客户端一致,无 hydration mismatch
|
// React 状态渲染,SSR/客户端一致,无 hydration mismatch
|
||||||
})();` }} />
|
})();` }} />
|
||||||
<ToastProvider>
|
<ToastProvider>
|
||||||
<I18nInit />
|
<I18nInit lng={lng} />
|
||||||
<CustomCssLoader />
|
<CustomCssLoader />
|
||||||
{children}
|
{children}
|
||||||
</ToastProvider>
|
</ToastProvider>
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
// i18n 客户端初始化(挂在 layout,hydrate 后执行)
|
// i18n 客户端 Provider:在 children 渲染前同步初始化 i18n
|
||||||
import { useEffect } from 'react';
|
// - lng 由 Server Component(layout)从 cookie / Accept-Language 推导传入
|
||||||
|
// - 同步 init(initImmediate:false)→ SSR 与客户端首次渲染语言一致,无 hydration mismatch
|
||||||
import { initI18n } from '@/lib/i18n';
|
import { initI18n } from '@/lib/i18n';
|
||||||
|
|
||||||
export default function I18nInit() {
|
export default function I18nProvider({ lng, children }) {
|
||||||
useEffect(() => {
|
// 函数体在 children 渲染前执行:useTranslation 组件拿到已初始化的 i18n
|
||||||
initI18n();
|
initI18n(lng);
|
||||||
}, []);
|
return <>{children}</>;
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
+24
-17
@@ -1,41 +1,48 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
// i18n 配置:i18next + react-i18next
|
// i18n 配置:i18next + react-i18next
|
||||||
// - 模块顶层无条件 init(SSR Node 与客户端都执行):SSR 输出用默认 zh,
|
// - initI18n(lng?):可传入初始语言(SSR 从 cookie/浏览器偏好推导),
|
||||||
// 与客户端初始语言一致 → 无 hydration mismatch
|
// 无传入时按 localStorage > 浏览器语言 > zh 自动选择
|
||||||
// - initI18n() 在客户端按 localStorage/浏览器语言切换;SSR 时 no-op
|
// - 顶层模块加载时不 init(由 I18nInit 在客户端 useEffect 调用),
|
||||||
|
// 保证 SSR/客户端首次渲染语言一致 → 无 hydration mismatch
|
||||||
import i18n from 'i18next';
|
import i18n from 'i18next';
|
||||||
import { initReactI18next } from 'react-i18next';
|
import { initReactI18next } from 'react-i18next';
|
||||||
import zh from '@/locales/zh.json';
|
import zh from '@/locales/zh.json';
|
||||||
import en from '@/locales/en.json';
|
import en from '@/locales/en.json';
|
||||||
|
|
||||||
|
let initialized = false;
|
||||||
|
|
||||||
|
export function initI18n(lng) {
|
||||||
|
if (initialized) {
|
||||||
|
// 已初始化:如果外部给了不同语言(如路由跳转后 cookie 变化)则切换
|
||||||
|
if (lng && i18n.language !== lng) i18n.changeLanguage(lng);
|
||||||
|
return i18n;
|
||||||
|
}
|
||||||
|
initialized = true;
|
||||||
|
if (!lng && typeof window !== 'undefined') {
|
||||||
|
const saved = localStorage.getItem('forumlify-lang');
|
||||||
|
const nav = (navigator.language || 'zh').toLowerCase();
|
||||||
|
lng = saved || (nav.startsWith('en') ? 'en' : 'zh');
|
||||||
|
}
|
||||||
i18n.use(initReactI18next).init({
|
i18n.use(initReactI18next).init({
|
||||||
resources: {
|
resources: {
|
||||||
zh: { translation: zh },
|
zh: { translation: zh },
|
||||||
en: { translation: en },
|
en: { translation: en },
|
||||||
},
|
},
|
||||||
lng: 'zh',
|
lng: lng || 'zh',
|
||||||
fallbackLng: 'zh',
|
fallbackLng: 'zh',
|
||||||
interpolation: { escapeValue: false },
|
interpolation: { escapeValue: false },
|
||||||
react: { useSuspense: false },
|
react: { useSuspense: false },
|
||||||
// 同步初始化:SSR 渲染时 t() 立即返回翻译(否则返回 key → hydration mismatch)
|
|
||||||
initImmediate: false,
|
initImmediate: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 客户端初始化:按 localStorage / 浏览器语言切换(SSR 阶段 no-op)
|
|
||||||
export function initI18n() {
|
|
||||||
if (typeof window === 'undefined') return i18n;
|
|
||||||
try {
|
|
||||||
const saved = localStorage.getItem('forumlify-lang');
|
|
||||||
const nav = (navigator.language || 'zh').toLowerCase();
|
|
||||||
const lng = saved || (nav.startsWith('en') ? 'en' : 'zh');
|
|
||||||
if (i18n.language !== lng) i18n.changeLanguage(lng);
|
|
||||||
} catch (e) {}
|
|
||||||
return i18n;
|
return i18n;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 切换语言(保存到 localStorage)
|
// 切换语言(保存到 localStorage + cookie,SSR 首帧即用正确语言)
|
||||||
export function setAppLanguage(lng) {
|
export function setAppLanguage(lng) {
|
||||||
if (typeof window !== 'undefined') localStorage.setItem('forumlify-lang', lng);
|
if (typeof window !== 'undefined') {
|
||||||
|
localStorage.setItem('forumlify-lang', lng);
|
||||||
|
document.cookie = 'forumlify-lang=' + lng + '; path=/; max-age=31536000';
|
||||||
|
}
|
||||||
return i18n.changeLanguage(lng);
|
return i18n.changeLanguage(lng);
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user