diff --git a/components/ui/language-switcher.tsx b/components/ui/language-switcher.tsx index 836aa82..295c096 100644 --- a/components/ui/language-switcher.tsx +++ b/components/ui/language-switcher.tsx @@ -23,6 +23,10 @@ export function LanguageSwitcher() { const handleChange = (e: React.ChangeEvent) => { const newLocale = e.target.value + + // ✅ 同步设置 cookie,供 middleware.ts 使用 + document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000` // 保存 1 年 + let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean) const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any) diff --git a/components/utility/home-redirector.tsx b/components/utility/home-redirector.tsx index 0672240..7836539 100644 --- a/components/utility/home-redirector.tsx +++ b/components/utility/home-redirector.tsx @@ -14,18 +14,21 @@ export default function HomeRedirector() { useEffect(() => { const preferred = localStorage.getItem('preferred-language') const currentPath = window.location.pathname - + console.log('[HomeRedirector] preferred:', preferred) console.log('[HomeRedirector] currentPath:', currentPath) - + if (!preferred || !isValidLocale(preferred)) { console.log('[HomeRedirector] No valid preferred language found.') return } - + + // ✅ 同步写入 cookie + document.cookie = `preferred-language=${preferred}; path=/; max-age=31536000` // 1 年 + const pathLocale = currentPath.split('/')[1] const hasLocaleInPath = isValidLocale(pathLocale) - + if (!hasLocaleInPath) { const newPath = `/${preferred}${currentPath}` console.log('[HomeRedirector] Redirecting to:', newPath) @@ -34,6 +37,7 @@ export default function HomeRedirector() { console.log('[HomeRedirector] Already has valid locale in path, skipping redirect.') } }, []) + return null }