This commit is contained in:
hailin 2025-04-17 11:38:53 +08:00
parent 1ff10621f1
commit 3b03eca2b4
1 changed files with 11 additions and 24 deletions

View File

@ -15,45 +15,32 @@ export function LanguageSwitcher() {
useEffect(() => {
if (typeof window !== 'undefined') {
const saved = localStorage.getItem('preferred-language')
console.log('[LanguageSwitcher] currentLocale:', currentLocale)
console.log('[LanguageSwitcher] saved preferred-language:', saved)
if (!saved || saved !== currentLocale) {
localStorage.setItem('preferred-language', currentLocale)
console.log('[LanguageSwitcher] preferred-language updated to:', currentLocale)
}
}
}, [currentLocale])
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newLocale = e.target.value
console.log('[LanguageSwitcher] User selected newLocale:', newLocale)
console.log('[LanguageSwitcher] Current pathname:', pathname)
if (typeof window !== 'undefined') {
localStorage.setItem('preferred-language', newLocale)
console.log('[LanguageSwitcher] Saved newLocale to localStorage')
}
let segments = pathname.split('/').filter(Boolean)
console.log('[LanguageSwitcher] Segments before change:', segments)
const localeList = [...i18nConfig.locales] as string[]
const isLocaleInPath = localeList.includes(segments[0])
console.log('[LanguageSwitcher] isLocaleInPath:', isLocaleInPath)
let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean)
const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any)
if (isLocaleInPath) {
segments[0] = newLocale
} else {
segments.unshift(newLocale)
}
const newPath = '/' + segments.join('/')
console.log('[LanguageSwitcher] Final newPath:', newPath)
startTransition(() => {
router.push(newPath)
router.refresh()
if (pathname !== newPath) {
router.push(newPath)
} else {
router.refresh()
}
})
}