This commit is contained in:
hailin 2025-04-17 13:13:05 +08:00
parent d6a7c26849
commit 6fbfbf53b8
2 changed files with 12 additions and 4 deletions

View File

@ -23,6 +23,10 @@ export function LanguageSwitcher() {
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newLocale = e.target.value
// ✅ 同步设置 cookie供 middleware.ts 使用
document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000` // 保存 1 年
let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean)
const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any)

View File

@ -14,18 +14,21 @@ export default function HomeRedirector() {
useEffect(() => {
const preferred = localStorage.getItem('preferred-language')
const currentPath = window.location.pathname
console.log('[HomeRedirector] 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 年
const pathLocale = currentPath.split('/')[1]
const hasLocaleInPath = isValidLocale(pathLocale)
if (!hasLocaleInPath) {
const newPath = `/${preferred}${currentPath}`
console.log('[HomeRedirector] Redirecting to:', newPath)
@ -34,6 +37,7 @@ export default function HomeRedirector() {
console.log('[HomeRedirector] Already has valid locale in path, skipping redirect.')
}
}, [])
return null
}