This commit is contained in:
hailin 2025-04-17 14:12:57 +08:00
parent 92adad6b80
commit 1fb0a45aa9
1 changed files with 5 additions and 8 deletions

View File

@ -13,25 +13,22 @@ export function LanguageSwitcher() {
const currentLocale = pathname.split('/')[1] || i18nConfig.defaultLocale
useEffect(() => {
// 只在加载时检查,避免多次保存 cookie
if (typeof window !== 'undefined') {
const saved = localStorage.getItem('preferred-language')
const isLocaleInPath = i18nConfig.locales.includes(currentLocale as any)
// 只有在 URL 中没有 locale 前缀时才写入 cookie 和 localStorage避免错误覆盖
// 只有在 URL 中没有 locale 前缀时才进行处理
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)
// 验证 cookie 是否成功写入
const cookieValue = document.cookie
console.log('[LanguageSwitcher] Current cookies:', cookieValue)
// 不做 cookie 写入,除非用户选择语言
console.log('[LanguageSwitcher] No need to update cookie, currentLocale:', currentLocale)
}
}
}, [currentLocale])
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newLocale = e.target.value
// 仅在用户选择语言后保存 cookie
document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000`
// 验证 cookie 是否成功写入