'use client' import i18nConfig from '@/i18nConfig' import { usePathname, useRouter } from 'next/navigation' import { useEffect, useTransition } from 'react' import { Globe } from 'lucide-react' export function LanguageSwitcher() { const router = useRouter() const pathname = usePathname() const [isPending, startTransition] = useTransition() const currentLocale = pathname.split('/')[1] || i18nConfig.defaultLocale useEffect(() => { // 第一次访问页面时,如果 URL 有语言,就记住 if (typeof window !== 'undefined') { const saved = localStorage.getItem('preferred-language') if (!saved || saved !== currentLocale) { localStorage.setItem('preferred-language', currentLocale) } } }, [currentLocale]) const handleChange = (e: React.ChangeEvent) => { const newLocale = e.target.value if (typeof window !== 'undefined') { localStorage.setItem('preferred-language', newLocale) } // 拆解当前路径 const segments = pathname.split('/') // 如果路径前缀是语言码,则替换 const isLocaleInPath = i18nConfig.locales.includes(segments[1]) if (isLocaleInPath) { segments[1] = newLocale } else { // 否则插入语言前缀 segments.unshift(newLocale) } const newPath = segments.join('/') startTransition(() => { router.push(newPath) router.refresh() }) } return (
) }