From 4a4caf8d78227f5c09f767727e691fe16336256c Mon Sep 17 00:00:00 2001 From: hailin Date: Thu, 17 Apr 2025 13:38:52 +0800 Subject: [PATCH] . --- components/ui/language-switcher.tsx | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/components/ui/language-switcher.tsx b/components/ui/language-switcher.tsx index b841a95..9368c52 100644 --- a/components/ui/language-switcher.tsx +++ b/components/ui/language-switcher.tsx @@ -15,20 +15,22 @@ export function LanguageSwitcher() { useEffect(() => { if (typeof window !== 'undefined') { const saved = localStorage.getItem('preferred-language') - if (!saved || saved !== currentLocale) { + const isLocaleInPath = i18nConfig.locales.includes(currentLocale as any) + + // ✅ 只有在 URL 中没有 locale 前缀时才写入 cookie 和 localStorage,避免错误覆盖 + if (!isLocaleInPath && saved !== currentLocale) { localStorage.setItem('preferred-language', currentLocale) + document.cookie = `preferred-language=${currentLocale}; path=/; max-age=31536000` + console.log('[LanguageSwitcher] set preferred-language to:', currentLocale) } } }, [currentLocale]) const handleChange = (e: React.ChangeEvent) => { const newLocale = e.target.value - - // ✅ 同步设置 cookie,供 middleware.ts 使用 - document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000` // 保存 1 年 + document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000` let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean) - const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any) if (isLocaleInPath) { @@ -39,8 +41,7 @@ export function LanguageSwitcher() { const newPath = '/' + segments.join('/') - - // 🔥 核心修复:延迟 router.push,确保 cookie 写入完成再跳转 + // ✅ 延迟跳转,确保 cookie 写入完成 setTimeout(() => { startTransition(() => { if (pathname !== newPath) { @@ -50,8 +51,6 @@ export function LanguageSwitcher() { } }) }, 0) - - } return (