This commit is contained in:
hailin 2025-04-17 13:51:15 +08:00
parent 4a4caf8d78
commit 6d3eaf1f33
1 changed files with 13 additions and 2 deletions

View File

@ -17,19 +17,30 @@ export function LanguageSwitcher() {
const saved = localStorage.getItem('preferred-language')
const isLocaleInPath = i18nConfig.locales.includes(currentLocale as any)
// 只有在 URL 中没有 locale 前缀时才写入 cookie 和 localStorage避免错误覆盖
// 只有在 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)
// 确保 cookie 写入
const cookieValue = document.cookie
console.log('[LanguageSwitcher] Cookie after setting:', cookieValue)
}
}
}, [currentLocale])
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newLocale = e.target.value
// 写入 cookie
document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000`
// 检查 cookie 是否正确写入
const cookieValue = document.cookie
console.log('[LanguageSwitcher] Cookie set to:', cookieValue)
let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean)
const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any)
@ -41,7 +52,7 @@ export function LanguageSwitcher() {
const newPath = '/' + segments.join('/')
// 延迟跳转,确保 cookie 写入完成
// 延迟跳转,确保 cookie 写入完成
setTimeout(() => {
startTransition(() => {
if (pathname !== newPath) {