This commit is contained in:
parent
8653187a04
commit
4a4caf8d78
|
|
@ -15,20 +15,22 @@ export function LanguageSwitcher() {
|
|||
useEffect(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const saved = localStorage.getItem('preferred-language')
|
||||
if (!saved || saved !== currentLocale) {
|
||||
const isLocaleInPath = i18nConfig.locales.includes(currentLocale as any)
|
||||
|
||||
// ✅ 只有在 URL 中没有 locale 前缀时才写入 cookie 和 localStorage,避免错误覆盖
|
||||
if (!isLocaleInPath && saved !== currentLocale) {
|
||||
localStorage.setItem('preferred-language', currentLocale)
|
||||
document.cookie = `preferred-language=${currentLocale}; path=/; max-age=31536000`
|
||||
console.log('[LanguageSwitcher] set preferred-language to:', currentLocale)
|
||||
}
|
||||
}
|
||||
}, [currentLocale])
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const newLocale = e.target.value
|
||||
|
||||
// ✅ 同步设置 cookie,供 middleware.ts 使用
|
||||
document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000` // 保存 1 年
|
||||
document.cookie = `preferred-language=${newLocale}; path=/; max-age=31536000`
|
||||
|
||||
let segments = pathname === '/' ? [] : pathname.split('/').filter(Boolean)
|
||||
|
||||
const isLocaleInPath = i18nConfig.locales.includes(segments[0] as any)
|
||||
|
||||
if (isLocaleInPath) {
|
||||
|
|
@ -39,8 +41,7 @@ export function LanguageSwitcher() {
|
|||
|
||||
const newPath = '/' + segments.join('/')
|
||||
|
||||
|
||||
// 🔥 核心修复:延迟 router.push,确保 cookie 写入完成再跳转
|
||||
// ✅ 延迟跳转,确保 cookie 写入完成
|
||||
setTimeout(() => {
|
||||
startTransition(() => {
|
||||
if (pathname !== newPath) {
|
||||
|
|
@ -50,8 +51,6 @@ export function LanguageSwitcher() {
|
|||
}
|
||||
})
|
||||
}, 0)
|
||||
|
||||
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
|
|||
Loading…
Reference in New Issue