This commit is contained in:
hailin 2025-04-17 12:04:32 +08:00
parent 4a3347c55c
commit bddd42e0db
1 changed files with 8 additions and 8 deletions

View File

@ -4,6 +4,11 @@ import { useEffect } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import i18nConfig from '@/i18nConfig' import i18nConfig from '@/i18nConfig'
const isValidLocale = (locale: string): boolean => {
const localeList = [...i18nConfig.locales] as string[]
return localeList.includes(locale)
}
export default function HomeRedirector() { export default function HomeRedirector() {
const router = useRouter() const router = useRouter()
@ -11,24 +16,19 @@ export default function HomeRedirector() {
const preferred = localStorage.getItem('preferred-language') const preferred = localStorage.getItem('preferred-language')
const currentPath = window.location.pathname const currentPath = window.location.pathname
console.log('[HomeRedirector] preferred:', preferred)
console.log('[HomeRedirector] currentPath:', currentPath) console.log('[HomeRedirector] currentPath:', currentPath)
console.log('[HomeRedirector] preferred-language from storage:', preferred)
const isValidLocale = (lang: string) =>
(i18nConfig.locales as string[]).includes(lang)
// 若路径中已经有 locale 前缀,或 preferred 为空 / 非法,跳过
if ( if (
preferred && preferred &&
isValidLocale(preferred) && isValidLocale(preferred) &&
!currentPath.startsWith(`/${preferred}/`) && !currentPath.startsWith(`/${preferred}/`)
!i18nConfig.locales.some(locale => currentPath.startsWith(`/${locale}/`))
) { ) {
const newPath = `/${preferred}${currentPath}` const newPath = `/${preferred}${currentPath}`
console.log('[HomeRedirector] Redirecting to:', newPath) console.log('[HomeRedirector] Redirecting to:', newPath)
router.replace(newPath) router.replace(newPath)
} else { } else {
console.log('[HomeRedirector] No redirection triggered') console.log('[HomeRedirector] No redirect needed.')
} }
}, []) }, [])