React TypeScript中i18next从API加载翻译及相关问题咨询
React TypeScript 中用 i18next 从 API 加载翻译、切换语言及同步 URL
一、从 API 加载翻译
方法1:使用官方 HTTP 后端(推荐)
借助 i18next-http-backend 插件实现异步加载,无需手动处理 API 请求:
- 安装依赖(若未安装)
npm install i18next-http-backend react-i18next i18next
- 配置 i18n(
i18n.ts)
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; i18n .use(Backend) .use(initReactI18next) .init({ fallbackLng: 'en', debug: false, interpolation: { escapeValue: false, // React 已自带转义,无需重复处理 }, backend: { loadPath: '/api/translations/{{lng}}', // 替换为你的 API 接口,返回对应语言的翻译 JSON // 可选:配置请求头、跨域等 // headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }, // requestOptions: { mode: 'cors' } }, react: { useSuspense: true, // 开启 Suspense 处理加载状态 }, }); export default i18n;
- 在组件中使用(配合 Suspense)
import { Suspense } from 'react'; import { useTranslation } from 'react-i18next'; function App() { return ( <Suspense fallback={<div>加载翻译中...</div>}> <PageContent /> </Suspense> ); } function PageContent() { const { t } = useTranslation(); return <h1>{t('welcome_message')}</h1>; }
方法2:自定义 API 加载逻辑
如果 API 返回格式特殊或需要额外处理,可手动实现加载逻辑:
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; // 自定义翻译加载函数 async function fetchTranslations(lng: string) { const res = await fetch(`/api/translations/${lng}`); if (!res.ok) throw new Error('加载翻译失败'); return res.json(); } // 初始化 i18n async function initI18n() { // 可从 URL、localStorage 读取初始语言 const initialLng = localStorage.getItem('i18nextLng') || 'en'; const translations = await fetchTranslations(initialLng); await i18n .use(initReactI18next) .init({ lng: initialLng, fallbackLng: 'en', debug: false, interpolation: { escapeValue: false, }, resources: { [initialLng]: { translation: translations }, }, }); } initI18n(); export default i18n;
二、实现语言切换按钮
通过 i18n.changeLanguage() 方法切换语言,可配合 localStorage 持久化选择:
import { useTranslation } from 'react-i18next'; // 定义支持的语言类型 type SupportedLng = 'en' | 'zh' | 'es'; function LanguageSwitcher() { const { i18n } = useTranslation(); const switchLanguage = (lng: SupportedLng) => { i18n.changeLanguage(lng); localStorage.setItem('i18nextLng', lng); // 持久化到本地存储 }; return ( <div className="language-switcher"> <button onClick={() => switchLanguage('en')}>English</button> <button onClick={() => switchLanguage('zh')}>中文</button> <button onClick={() => switchLanguage('es')}>Español</button> </div> ); } export default LanguageSwitcher;
三、同步语言环境到 URL
i18n 本身不直接修改 URL,但可结合路由或手动操作 URL 实现同步,以下是两种常见方案:
方案1:React Router 路径参数(推荐)
假设路由结构为 /[lng]/[page],比如 /en/home、/zh/home:
- 路由配置(
router.tsx)
import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom'; import App from './App'; import Home from './pages/Home'; import About from './pages/About'; const router = createBrowserRouter([ { path: '/:lng', element: <App />, children: [ { path: 'home', element: <Home /> }, { path: 'about', element: <About /> }, ], }, // 根路径重定向到默认语言 { path: '/', element: <Navigate to="/en/home" replace /> }, ]); export function Root() { return <RouterProvider router={router} />; }
- 语言切换时同步 URL
import { useTranslation } from 'react-i18next'; import { useNavigate, useParams } from 'react-router-dom'; import type { SupportedLng } from './types'; function LanguageSwitcher() { const { i18n } = useTranslation(); const navigate = useNavigate(); const { lng } = useParams<{ lng: SupportedLng }>(); const switchLanguage = (newLng: SupportedLng) => { i18n.changeLanguage(newLng); localStorage.setItem('i18nextLng', newLng); // 修改路径中的语言参数 const currentPath = window.location.pathname.replace(`/${lng}`, `/${newLng}`); navigate(currentPath, { replace: true }); // replace 避免历史记录堆积 }; return ( <div> <button onClick={() => switchLanguage('en')}>English</button> <button onClick={() => switchLanguage('zh')}>中文</button> </div> ); }
- 初始化时从 URL 读取语言
在i18n.ts的初始化逻辑中,从路径参数获取初始语言:
const initialLng = window.location.pathname.split('/')[1] as SupportedLng || 'en';
方案2:URL 查询参数
通过 URL 的 lng 查询参数同步,比如 /?lng=en:
import { useTranslation } from 'react-i18next'; import type { SupportedLng } from './types'; function LanguageSwitcher() { const { i18n } = useTranslation(); const switchLanguage = (newLng: SupportedLng) => { i18n.changeLanguage(newLng); localStorage.setItem('i18nextLng', newLng); // 修改 URL 查询参数 const url = new URL(window.location.href); url.searchParams.set('lng', newLng); window.history.replaceState({}, '', url.toString()); }; return ( <div> <button onClick={() => switchLanguage('en')}>English</button> <button onClick={() => switchLanguage('zh')}>中文</button> </div> ); }
初始化时从查询参数读取:
const urlParams = new URLSearchParams(window.location.search); const initialLng = urlParams.get('lng') as SupportedLng || 'en';
内容的提问来源于stack exchange,提问作者Sonal
相关产品推荐
相关产品推荐

