i18next如何实现切换语言时URL自动添加对应locale路径参数
React多语言切换自动更新URL locale配置方案
步骤1:调整i18n初始化配置
首先修正语言检测优先级,优先从URL路径读取语言标识,同时移除硬编码的默认lng配置避免覆盖路径检测结果:
// 修改i18n配置的detection顺序和初始化参数 const options = { // 把path放在最前面,优先读取路径中的locale order: ['path', 'localStorage', 'querystring', 'navigator'], // 其余原有配置保持不变 lookupQuerystring: 'lng', lookupCookie: 'i18next', lookupLocalStorage: 'i18nextLng', lookupSessionStorage: 'i18nextLng', lookupFromPathIndex: 0, lookupFromSubdomainIndex: 0, caches: [ 'localStorage', 'cookie', ], excludeCacheFor: ['cimode'], cookieMinutes: 10, cookieDomain: 'myDomain', htmlTag: document.documentElement, cookieOptions: { path: '/', sameSite: 'strict' } } i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) .init({ fallbackLng: "ar", // 删除硬编码的lng: 'en' 配置,让语言检测器自动读取路径值 debug: true, whitelist: languages, checkWhitelist: true , detection: options, interpolation: { escapeValue: false, } });
步骤2:修改语言切换逻辑,同步更新路由
在切换语言的函数中加入路由跳转逻辑,自动替换路径中的语言标识,这里分React Router v5和v6两种写法:
React Router v5 写法
import { useHistory } from 'react-router-dom'; import i18n from '你的i18n配置文件路径'; const DropDownMenu = () => { const history = useHistory(); const supportedLngs = ["en", "es", "ar"]; const handleClick = (newLng) => { i18n.changeLanguage(newLng); // 处理当前路径,替换语言标识 const pathSegments = window.location.pathname.split('/').filter(Boolean); if (supportedLngs.includes(pathSegments[0])) { pathSegments[0] = newLng; } else { pathSegments.unshift(newLng); } history.push(`/${pathSegments.join('/')}${window.location.search}`); } // 原有菜单渲染逻辑保持不变 }
React Router v6 写法
import { useNavigate } from 'react-router-dom'; import i18n from '你的i18n配置文件路径'; const DropDownMenu = () => { const navigate = useNavigate(); const supportedLngs = ["en", "es", "ar"]; const handleClick = (newLng) => { i18n.changeLanguage(newLng); const pathSegments = window.location.pathname.split('/').filter(Boolean); if (supportedLngs.includes(pathSegments[0])) { pathSegments[0] = newLng; } else { pathSegments.unshift(newLng); } navigate(`/${pathSegments.join('/')}${window.location.search}`); } // 原有菜单渲染逻辑保持不变 }
步骤3:统一路由配置,添加全局locale前缀
将所有业务路由包裹在带lng参数的父路由下,同时添加无locale路径的自动重定向逻辑:
// React Router v5 示例 import { Switch, Route, Redirect } from 'react-router-dom'; const supportedLngs = ["en", "es", "ar"]; <Switch> {/* 匹配带locale的所有路径 */} <Route path="/:lng" render={(routeProps) => { const lng = routeProps.match.params.lng; // 校验locale是否合法,不合法跳转404或者默认语言 if (!supportedLngs.includes(lng)) { return <Redirect to="/en" /> } return ( <> {/* 所有业务路由放在这里 */} <Route exact path={`/:lng/services/edit`} render={(routeProps) => ( <MainLayout> <ServicesEdit {...routeProps} isEdit /> </MainLayout> )} /> {/* 其他业务路由同理配置 */} </> ) }} /> {/* 无locale的路径自动重定向到默认语言路径 */} <Redirect from="*" to={`/en${window.location.pathname}${window.location.search}`} /> </Switch>
步骤4:封装自定义Link组件(可选,优化开发体验)
避免每次手动拼接locale前缀,封装统一的链接组件:
import { Link as RouterLink } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; const LocaleLink = ({ to, ...props }) => { const { i18n } = useTranslation(); const currentLng = i18n.language; const processedPath = to.startsWith('/') ? `/${currentLng}${to}` : `/${currentLng}/${to}`; return <RouterLink to={processedPath} {...props} /> }; // 使用时直接写业务路径即可,自动拼接locale <LocaleLink to="/services/edit">{t("SERVICES_EDIT_PAGE")}</LocaleLink>
内容的提问来源于stack exchange,提问作者user16050054
相关产品推荐
相关产品推荐

