This commit is contained in:
parent
d6a7c26849
commit
6fbfbf53b8
|
|
@ -23,6 +23,10 @@ export function LanguageSwitcher() {
|
||||||
|
|
||||||
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
const newLocale = e.target.value
|
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)
|
let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean)
|
||||||
|
|
||||||
const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any)
|
const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any)
|
||||||
|
|
|
||||||
|
|
@ -14,18 +14,21 @@ export default function HomeRedirector() {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
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 (!preferred || !isValidLocale(preferred)) {
|
if (!preferred || !isValidLocale(preferred)) {
|
||||||
console.log('[HomeRedirector] No valid preferred language found.')
|
console.log('[HomeRedirector] No valid preferred language found.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ✅ 同步写入 cookie
|
||||||
|
document.cookie = `preferred-language=${preferred}; path=/; max-age=31536000` // 1 年
|
||||||
|
|
||||||
const pathLocale = currentPath.split('/')[1]
|
const pathLocale = currentPath.split('/')[1]
|
||||||
const hasLocaleInPath = isValidLocale(pathLocale)
|
const hasLocaleInPath = isValidLocale(pathLocale)
|
||||||
|
|
||||||
if (!hasLocaleInPath) {
|
if (!hasLocaleInPath) {
|
||||||
const newPath = `/${preferred}${currentPath}`
|
const newPath = `/${preferred}${currentPath}`
|
||||||
console.log('[HomeRedirector] Redirecting to:', newPath)
|
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.')
|
console.log('[HomeRedirector] Already has valid locale in path, skipping redirect.')
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue