This commit is contained in:
hailin 2025-04-17 13:38:52 +08:00
parent 8653187a04
commit 4a4caf8d78
1 changed files with 8 additions and 9 deletions

View File

@ -15,20 +15,22 @@ export function LanguageSwitcher() {
useEffect(() => { useEffect(() => {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const saved = localStorage.getItem('preferred-language') 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) localStorage.setItem('preferred-language', currentLocale)
document.cookie = `preferred-language=${currentLocale}; path=/; max-age=31536000`
console.log('[LanguageSwitcher] set preferred-language to:', currentLocale)
} }
} }
}, [currentLocale]) }, [currentLocale])
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newLocale = e.target.value const newLocale = e.target.value
document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000`
// ✅ 同步设置 cookie供 middleware.ts 使用
document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000` // 保存 1 年
let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean) let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean)
const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any) const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any)
if (isLocaleInPath) { if (isLocaleInPath) {
@ -39,8 +41,7 @@ export function LanguageSwitcher() {
const newPath = '/' + segments.join('/') const newPath = '/' + segments.join('/')
// ✅ 延迟跳转,确保 cookie 写入完成
// 🔥 核心修复:延迟 router.push确保 cookie 写入完成再跳转
setTimeout(() => { setTimeout(() => {
startTransition(() => { startTransition(() => {
if (pathname !== newPath) { if (pathname !== newPath) {
@ -50,8 +51,6 @@ export function LanguageSwitcher() {
} }
}) })
}, 0) }, 0)
} }
return ( return (