This commit is contained in:
hailin 2025-04-17 13:00:04 +08:00
parent ec9a1cbe31
commit f2130d7010
1 changed files with 13 additions and 13 deletions

View File

@ -1,37 +1,37 @@
'use client' 'use client'
import { useEffect } from 'react' import { useEffect } from 'react'
import { useRouter, usePathname } from 'next/navigation' import { useRouter } from 'next/navigation'
import i18nConfig from '@/i18nConfig' import i18nConfig from '@/i18nConfig'
const isValidLocale = (locale: string): boolean => { const isValidLocale = (locale: string): locale is (typeof i18nConfig.locales)[number] => {
const localeList = [...i18nConfig.locales] as string[] return (i18nConfig.locales as readonly string[]).includes(locale)
return localeList.includes(locale)
} }
export default function HomeRedirector() { export default function HomeRedirector() {
const router = useRouter() const router = useRouter()
const pathname = usePathname()
useEffect(() => { useEffect(() => {
if (pathname !== '/') return
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] preferred:', preferred)
console.log('[HomeRedirector] currentPath:', currentPath) console.log('[HomeRedirector] currentPath:', currentPath)
if ( if (!preferred || !isValidLocale(preferred)) {
preferred && console.log('[HomeRedirector] No valid preferred language found.')
isValidLocale(preferred) && return
!currentPath.startsWith(`/${preferred}/`) }
) {
const pathLocale = currentPath.split('/')[1]
const hasLocaleInPath = isValidLocale(pathLocale)
if (!hasLocaleInPath) {
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 redirect needed.') console.log('[HomeRedirector] Already has valid locale in path, skipping redirect.')
} }
}, []) }, [])