From f2130d70106aade64532fa2e253a1d1b46d70e22 Mon Sep 17 00:00:00 2001 From: hailin Date: Thu, 17 Apr 2025 13:00:04 +0800 Subject: [PATCH] . --- components/utility/home-redirector.tsx | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/components/utility/home-redirector.tsx b/components/utility/home-redirector.tsx index 90f4cfd..0672240 100644 --- a/components/utility/home-redirector.tsx +++ b/components/utility/home-redirector.tsx @@ -1,37 +1,37 @@ 'use client' import { useEffect } from 'react' -import { useRouter, usePathname } from 'next/navigation' +import { useRouter } from 'next/navigation' import i18nConfig from '@/i18nConfig' -const isValidLocale = (locale: string): boolean => { - const localeList = [...i18nConfig.locales] as string[] - return localeList.includes(locale) +const isValidLocale = (locale: string): locale is (typeof i18nConfig.locales)[number] => { + return (i18nConfig.locales as readonly string[]).includes(locale) } export default function HomeRedirector() { const router = useRouter() - const pathname = usePathname() useEffect(() => { - if (pathname !== '/') return - 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) && - !currentPath.startsWith(`/${preferred}/`) - ) { + if (!preferred || !isValidLocale(preferred)) { + console.log('[HomeRedirector] No valid preferred language found.') + return + } + + const pathLocale = currentPath.split('/')[1] + const hasLocaleInPath = isValidLocale(pathLocale) + + if (!hasLocaleInPath) { const newPath = `/${preferred}${currentPath}` console.log('[HomeRedirector] Redirecting to:', newPath) router.replace(newPath) } else { - console.log('[HomeRedirector] No redirect needed.') + console.log('[HomeRedirector] Already has valid locale in path, skipping redirect.') } }, [])