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,32 +15,17 @@ 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')
console.log('[LanguageSwitcher] currentLocale:', currentLocale)
console.log('[LanguageSwitcher] saved preferred-language:', saved)
if (!saved || saved !== currentLocale) { if (!saved || saved !== currentLocale) {
localStorage.setItem('preferred-language', currentLocale) localStorage.setItem('preferred-language', currentLocale)
console.log('[LanguageSwitcher] preferred-language updated 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
console.log('[LanguageSwitcher] User selected newLocale:', newLocale) let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean)
console.log('[LanguageSwitcher] Current pathname:', pathname)
if (typeof window !== 'undefined') { const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any)
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)
if (isLocaleInPath) { if (isLocaleInPath) {
segments[0] = newLocale segments[0] = newLocale
@ -49,11 +34,13 @@ export function LanguageSwitcher() {
} }
const newPath = '/' + segments.join('/') const newPath = '/' + segments.join('/')
console.log('[LanguageSwitcher] Final newPath:', newPath)
startTransition(() => { startTransition(() => {
router.push(newPath) if (pathname !== newPath) {
router.refresh() router.push(newPath)
} else {
router.refresh()
}
}) })
} }