49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect } from 'react'
|
|
import { useRouter } from 'next/navigation'
|
|
import i18nConfig from '@/i18nConfig'
|
|
import { useTranslation } from 'react-i18next' // 引入 useTranslation
|
|
|
|
const isValidLocale = (locale: string): locale is (typeof i18nConfig.locales)[number] => {
|
|
return (i18nConfig.locales as readonly string[]).includes(locale)
|
|
}
|
|
|
|
export default function HomeRedirector() {
|
|
const router = useRouter()
|
|
const { i18n } = useTranslation() // 获取 i18n 实例
|
|
|
|
useEffect(() => {
|
|
const preferred = localStorage.getItem('preferred-language')
|
|
const currentPath = window.location.pathname
|
|
|
|
console.log('[HomeRedirector] localStorage preferred:', preferred)
|
|
console.log('[HomeRedirector] currentPath:', currentPath)
|
|
|
|
if (!preferred || !isValidLocale(preferred)) {
|
|
console.log('[HomeRedirector] No valid preferred language found.')
|
|
return
|
|
}
|
|
|
|
// ✅ 同步写入 cookie
|
|
//document.cookie = `preferred-language=${preferred}; path=/; max-age=31536000` // 1 年
|
|
|
|
// 修改 i18n 中的语言
|
|
i18n.changeLanguage(preferred) // 更新 i18n 的 locale
|
|
|
|
const pathLocale = currentPath.split('/')[1]
|
|
const hasLocaleInPath = isValidLocale(pathLocale)
|
|
|
|
if (!hasLocaleInPath) {
|
|
const newPath = `/${preferred}${currentPath}`
|
|
console.log('[HomeRedirector] Redirecting to:', newPath)
|
|
router.replace(newPath)
|
|
} else {
|
|
console.log('[HomeRedirector] Skipping redirect.')
|
|
}
|
|
}, [])
|
|
|
|
|
|
return null
|
|
}
|