diff --git a/app/[locale]/page.tsx b/app/[locale]/page.tsx index 29da303..a2ef13f 100644 --- a/app/[locale]/page.tsx +++ b/app/[locale]/page.tsx @@ -5,6 +5,9 @@ import { IconArrowRight } from "@tabler/icons-react" import { useTheme } from "next-themes" import Link from "next/link" +import HomeRedirector from "@/components/utility/home-redirector" + + import { LanguageSwitcher } from '@/components/ui/language-switcher' export default function HomePage() { @@ -13,6 +16,7 @@ export default function HomePage() { return (
+
diff --git a/components/ui/language-switcher.tsx b/components/ui/language-switcher.tsx index b7276dd..1c627f6 100644 --- a/components/ui/language-switcher.tsx +++ b/components/ui/language-switcher.tsx @@ -2,7 +2,7 @@ import i18nConfig from '@/i18nConfig' import { usePathname, useRouter } from 'next/navigation' -import { useTransition } from 'react' +import { useEffect, useTransition } from 'react' import { Globe } from 'lucide-react' export function LanguageSwitcher() { @@ -12,8 +12,25 @@ export function LanguageSwitcher() { 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('/') segments[1] = newLocale const newPath = segments.join('/') diff --git a/components/utility/home-redirector.tsx b/components/utility/home-redirector.tsx new file mode 100644 index 0000000..fd3c99f --- /dev/null +++ b/components/utility/home-redirector.tsx @@ -0,0 +1,25 @@ +'use client' + +import { useEffect } from 'react' +import { useRouter } from 'next/navigation' +import i18nConfig from '@/i18nConfig' + +export default function HomeRedirector() { + const router = useRouter() + + useEffect(() => { + const preferred = localStorage.getItem('preferred-language') + const currentPath = window.location.pathname + + if ( + preferred && + i18nConfig.locales.includes(preferred) && + !currentPath.startsWith(`/${preferred}/`) + ) { + const newPath = `/${preferred}${currentPath}` + router.replace(newPath) + } + }, []) + + return null +}