Skip to content

Let's use AI to Earn!

feat: 新增按钮切换语言

gaoSirdcf9e660238e
diff --git a/src/app/context/LanguageContext.tsx b/src/app/context/LanguageContext.tsx
deleted file mode 100644
index 5691f88d..00000000
--- a/src/app/context/LanguageContext.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-"use client";
-
-import React, { createContext, useContext, useState, useEffect } from 'react';
-import { useRouter, usePathname } from 'next/navigation';
-import { languages } from '@/app/i18n/settings';
-
-type Language = typeof languages[number];
-
-interface LanguageContextType {
- language: Language;
- setLanguage: (lang: Language) => void;
-}
-
-const LanguageContext = createContext<LanguageContextType | undefined>(undefined);
-
-export function LanguageProvider({ children }: { children: React.ReactNode }) {
- const router = useRouter();
- const pathname = usePathname();
- const [language, setLanguageState] = useState<Language>('zh-CN');
-
- useEffect(() => {
- // 从URL中获取语言设置
- const pathSegments = pathname.split('/');
- const langFromPath = pathSegments[1];
- if (languages.includes(langFromPath as Language)) {
- setLanguageState(langFromPath as Language);
- }
- }, [pathname]);
-
- const setLanguage = (newLang: Language) => {
- setLanguageState(newLang);
- // 更新URL
- const pathSegments = pathname.split('/');
- if (languages.includes(pathSegments[1] as Language)) {
- pathSegments[1] = newLang;
- } else {
- pathSegments.splice(1, 0, newLang);
- }
- const newPath = pathSegments.join('/');
- // 使用 replace 而不是 push,这样不会在历史记录中创建新条目
- router.replace(newPath);
- };
-
- return (
- <LanguageContext.Provider value={{ language, setLanguage }}>
- {children}
- </LanguageContext.Provider>
- );
-}
-
-export function useLanguage() {
- const context = useContext(LanguageContext);
- if (context === undefined) {
- throw new Error('useLanguage must be used within a LanguageProvider');
- }
- return context;
-}
\ No newline at end of file
diff --git a/src/app/i18n/client.ts b/src/app/i18n/client.ts
index 44a52cca..b9cdd473 100644
--- a/src/app/i18n/client.ts
+++ b/src/app/i18n/client.ts
@@ -11,9 +11,9 @@ import {
import resourcesToBackend from "i18next-resources-to-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { cookieName, getOptions, languages } from "./settings";
-import { useParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import { getCookie, setCookie } from "cookies-next";
+import { useGetClientLng } from "@/hooks/useSystem";
const runsOnServerSide = typeof window === "undefined";
@@ -45,26 +45,26 @@ export function useTransClient<
options?: UseTranslationOptions<KPrefix>,
): UseTranslationResponse<FallbackNs<Ns>, KPrefix> {
const i18nextCookie = getCookie(cookieName);
- const lng = useParams()?.lng;
+ const lng = useGetClientLng();
if (typeof lng !== "string")
throw new Error("useT is only available inside /app/[lng]");
- const [activeLng, setActiveLng] = useState(i18next.resolvedLanguage);
-
- useEffect(() => {
- if (!lng || i18next.resolvedLanguage === lng) return;
- i18next.changeLanguage(lng).then(() => {
- setActiveLng(lng);
- });
- }, [lng]);
-
- useEffect(() => {
- if (i18nextCookie === lng) return;
- setCookie(cookieName, lng, { path: "/" });
- }, [lng, i18nextCookie]);
-
- return useTranslation(ns, {
- ...options,
- lng: activeLng,
- });
+ if (runsOnServerSide && i18next.resolvedLanguage !== lng) {
+ i18next.changeLanguage(lng);
+ } else {
+ const [activeLng, setActiveLng] = useState(i18next.resolvedLanguage);
+ useEffect(() => {
+ if (activeLng === i18next.resolvedLanguage) return;
+ setActiveLng(i18next.resolvedLanguage);
+ }, [activeLng, i18next.resolvedLanguage]);
+ useEffect(() => {
+ if (!lng || i18next.resolvedLanguage === lng) return;
+ i18next.changeLanguage(lng);
+ }, [lng, i18next]);
+ useEffect(() => {
+ if (i18nextCookie === lng) return;
+ setCookie(cookieName, lng, { path: "/" });
+ }, [lng, i18nextCookie]);
+ }
+ return useTranslation(ns, options);
}
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
deleted file mode 100644
index 14b59e89..00000000
--- a/src/app/layout.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { LanguageProvider } from './context/LanguageContext';
-
-export default function RootLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
- return (
- <html>
- <body>
- <LanguageProvider>
- {children}
- </LanguageProvider>
- </body>
- </html>
- );
-}
\ No newline at end of file
diff --git a/src/app/layout/layoutNav.tsx b/src/app/layout/layoutNav.tsx
index 691047a3..260c4383 100644
--- a/src/app/layout/layoutNav.tsx
+++ b/src/app/layout/layoutNav.tsx
@@ -7,12 +7,18 @@ import {
routerData,
} from "@/app/layout/routerData";
import Link from "next/link";
-import { MenuFoldOutlined, RightOutlined, UpOutlined, GlobalOutlined } from "@ant-design/icons";
+import {
+ MenuFoldOutlined,
+ RightOutlined,
+ UpOutlined,
+ GlobalOutlined,
+} from "@ant-design/icons";
import Image from "next/image";
import React, { useEffect, useRef, useState } from "react";
import { Drawer, Menu, Button } from "antd";
import { useRouter, useSelectedLayoutSegments } from "next/navigation";
-import { useLanguage } from "@/app/context/LanguageContext";
+import { useTransClient } from "@/app/i18n/client";
+import { useGetClientLng } from "@/hooks/useSystem";
/**
*
@@ -161,7 +167,8 @@ function ChildNav({
function NavPC() {
const [activeNav, setActiveNav] = useState("");
- const { language, setLanguage } = useLanguage();
+ const { t } = useTransClient();
+ const lng = useGetClientLng();
const timer = useRef<NodeJS.Timeout>();
const route = useSelectedLayoutSegments();
let currRouter = "/";
@@ -173,7 +180,8 @@ function NavPC() {
}
const toggleLanguage = () => {
- setLanguage(language === "zh-CN" ? "en" : "zh-CN");
+ const newLng = lng === "zh-CN" ? "en" : "zh-CN";
+ location.href = `/${newLng}` + location.pathname.replace(`/${lng}`, "");
};
return (
@@ -208,13 +216,13 @@ function NavPC() {
);
})}
</ul>
- <Button
- type="text"
- icon={<GlobalOutlined />}
+ <Button
+ type="text"
+ icon={<GlobalOutlined />}
onClick={toggleLanguage}
className={styles.languageButton}
>
- {language === "zh-CN" ? "EN" : "中文"}
+ {lng === "zh-CN" ? "EN" : "中文"}
</Button>
</div>
);
diff --git a/src/utils/request.ts b/src/utils/request.ts
index 3de505dc..da0146b9 100644
--- a/src/utils/request.ts
+++ b/src/utils/request.ts
@@ -2,6 +2,7 @@ import FetchService from "@/utils/FetchService/FetchService";
import { RequestParams } from "@/utils/FetchService/types";
import { useUserStore } from "@/store/user";
import { message } from "antd";
+import { useGetClientLng } from "@/hooks/useSystem";
type ResponseType<T> = {
code: string | number;
@@ -32,6 +33,13 @@ export async function request<T>(params: RequestParams) {
const res = await fetchService.request(params);
const data: ResponseType<T> = await res.json();
+ // 语言拦截
+ if (typeof window !== "undefined") {
+ const lng = useGetClientLng();
+ console.log(lng);
+ // ...
+ }
+
// @ts-ignore
if (data.code === "1" && data.data.statusCode === 401) {
useUserStore.getState().logout();