Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
perf: Optimize the issue where the language switch when entering a page is English first and then Chinese
gaoSir2deac0834bc2
diff --git a/src/app/i18n/client.ts b/src/app/i18n/client.tsindex 1abbdfe7..27f7a713 100644--- a/src/app/i18n/client.ts+++ b/src/app/i18n/client.ts@@ -30,15 +30,11 @@ i18next// .use(LocizeBackend) // locize backend could be used on client side, but prefer to keep it in sync with server side.init({...getOptions(undefined), // 不传递 lng 参数,让 i18next 自动检测+ lng: undefined, // let detect the language on client sidedetection: {order: ["path", "htmlTag", "cookie", "navigator"],- caches: ["cookie"], // 只缓存到 cookie,避免其他缓存干扰},preload: runsOnServerSide ? languages : [],- // 确保语言切换时立即生效- // react: {- // useSuspense: false,- // },});export function useTransClient<@@ -57,17 +53,17 @@ export function useTransClient<i18next.changeLanguage(lng);} else {const [activeLng, setActiveLng] = useState(i18next.resolvedLanguage);-+// 监听 i18next 语言变化useEffect(() => {if (activeLng === i18next.resolvedLanguage) return;setActiveLng(i18next.resolvedLanguage);}, [activeLng, i18next.resolvedLanguage]);-+// 强制同步 URL 参数中的语言到 i18nextuseEffect(() => {if (!lng) return;-+// 始终使用 URL 参数中的语言,忽略 i18next 的自动检测if (i18next.resolvedLanguage !== lng) {i18next.changeLanguage(lng).then(() => {@@ -79,7 +75,7 @@ export function useTransClient<setActiveLng(lng);}}, [lng]);-+// 同步 cookieuseEffect(() => {if (i18nextCookie === lng) return;diff --git a/src/components/common/LanguageSwitcher.tsx b/src/components/common/LanguageSwitcher.tsxindex 477fcbeb..307dd0e8 100644--- a/src/components/common/LanguageSwitcher.tsx+++ b/src/components/common/LanguageSwitcher.tsx@@ -4,26 +4,28 @@ import { Button, Dropdown, MenuProps } from "antd";import { CaretDownOutlined } from "@ant-design/icons";import Image from "next/image";import { useRouter } from "next/navigation";-import { useUserStore } from "@/store/user";import zhLang from "@/assets/images/zh.png";import enLang from "@/assets/images/us.png";+import { useGetClientLng } from "@/hooks/useSystem";export interface LanguageSwitcherProps {className?: string;style?: React.CSSProperties;- size?: 'small' | 'middle' | 'large';+ size?: "small" | "middle" | "large";}-const LanguageSwitcher = ({ className, style, size = 'middle' }: LanguageSwitcherProps) => {- const userStore = useUserStore();+const LanguageSwitcher = ({+ className,+ style,+ size = "middle",+}: LanguageSwitcherProps) => {+ const lang = useGetClientLng();const router = useRouter();const handleLanguageChange = (newLng: string) => {- userStore.setLang(newLng);-// 获取当前路径并替换语言前缀const currentPath = location.pathname;- const pathWithoutLang = currentPath.replace(`/${userStore.lang}`, "") || "/";+ const pathWithoutLang = currentPath.replace(`/${lang}`, "") || "/";const newPath = `/${newLng}${pathWithoutLang}`;router.push(newPath);@@ -32,60 +34,72 @@ const LanguageSwitcher = ({ className, style, size = 'middle' }: LanguageSwitche// 语言选项配置const languageOptions = [{- key: 'en',- label: 'English',+ key: "en",+ label: "English",flag: enLang,- current: userStore.lang === 'en'+ current: lang === "en",},{- key: 'zh-CN',- label: '简体中文',+ key: "zh-CN",+ label: "简体中文",flag: zhLang,- current: userStore.lang === 'zh-CN'- }+ current: lang === "zh-CN",+ },];- const currentLanguage = languageOptions.find(lang => lang.current) || languageOptions[0];+ const currentLanguage =+ languageOptions.find((lang) => lang.current) || languageOptions[0];- const languageMenuItems: MenuProps['items'] = languageOptions.map(option => ({- key: option.key,- label: (- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <Image- src={option.flag}- alt={option.label}- width={16}- height={16}- style={{ borderRadius: '50%' }}- />- <span style={{ color: option.current ? '#52c41a' : '#000' }}>{option.label}</span>+ const languageMenuItems: MenuProps["items"] = languageOptions.map(+ (option) => ({+ key: option.key,+ label: (+ <div+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ width: "100%",+ }}+ >+ <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>+ <Image+ src={option.flag}+ alt={option.label}+ width={16}+ height={16}+ style={{ borderRadius: "50%" }}+ />+ <span style={{ color: option.current ? "#52c41a" : "#000" }}>+ {option.label}+ </span>+ </div>+ {option.current && <span style={{ color: "#52c41a" }}>✓</span>}</div>- {option.current && <span style={{ color: '#52c41a' }}>✓</span>}- </div>- ),- onClick: () => handleLanguageChange(option.key)- }));+ ),+ onClick: () => handleLanguageChange(option.key),+ }),+ );const getButtonSize = () => {switch (size) {- case 'small':+ case "small":return {- padding: '2px 6px',- fontSize: '10px',- iconSize: 12+ padding: "2px 6px",+ fontSize: "10px",+ iconSize: 12,};- case 'large':+ case "large":return {- padding: '6px 12px',- fontSize: '14px',- iconSize: 16+ padding: "6px 12px",+ fontSize: "14px",+ iconSize: 16,};default:return {- padding: '4px 8px',- fontSize: '12px',- iconSize: 14+ padding: "4px 8px",+ fontSize: "12px",+ iconSize: 14,};}};@@ -95,23 +109,23 @@ const LanguageSwitcher = ({ className, style, size = 'middle' }: LanguageSwitchereturn (<Dropdownmenu={{ items: languageMenuItems }}- trigger={['click']}+ trigger={["click"]}placement="bottomRight"><Buttontype="text"className={className}style={{- display: 'flex',- alignItems: 'center',- gap: '8px',- padding: '4px 8px',- height: 'auto',- fontSize: '12px',- backgroundColor: '#fff',- border: '1px solid #EBEDEC',- borderRadius: '30px',- ...style+ display: "flex",+ alignItems: "center",+ gap: "8px",+ padding: "4px 8px",+ height: "auto",+ fontSize: "12px",+ backgroundColor: "#fff",+ border: "1px solid #EBEDEC",+ borderRadius: "30px",+ ...style,}}><Image@@ -119,9 +133,9 @@ const LanguageSwitcher = ({ className, style, size = 'middle' }: LanguageSwitchealt={currentLanguage.label}width={buttonConfig.iconSize}height={buttonConfig.iconSize}- style={{ borderRadius: '50%' }}+ style={{ borderRadius: "50%" }}/>- <span style={{ fontSize: '12px' }}>{currentLanguage.label}</span>+ <span style={{ fontSize: "12px" }}>{currentLanguage.label}</span><CaretDownOutlined style={{ fontSize: buttonConfig.fontSize }} /></Button></Dropdown>diff --git a/src/store/user.ts b/src/store/user.tsindex ac6951b8..c1287cdd 100644--- a/src/store/user.ts+++ b/src/store/user.ts@@ -1,5 +1,6 @@import { createPersistStore } from "@/utils/createPersistStore";import { getUserInfoApi } from "@/api/apiReq";+import i18next from "i18next";export interface UserInfo {createTime: string;@@ -21,7 +22,15 @@ export interface UserInfo {id: string;expireTime: string;startTime: string;- status: 'none' | 'trialing' | 'monthly_once' | 'yearly_once' | 'active_monthly' | 'active_yearly' | 'active_nonrenewing' | 'expired';+ status:+ | "none"+ | "trialing"+ | "monthly_once"+ | "yearly_once"+ | "active_monthly"+ | "active_yearly"+ | "active_nonrenewing"+ | "expired";_id: string;};}@@ -38,7 +47,7 @@ const state: IUserStore = {userInfo: {},// 添加账户是否默认开启代理isAddAccountPorxy: false,- lang: "",+ lang: i18next.language || "en",};export const useUserStore = createPersistStore(