React结合i18n实现切换语言时URL新增对应locale标识的问题咨询
调整方案
1. 修改i18n配置
优先从URL路径读取locale标识,同时移除硬编码的默认语言配置,避免覆盖路径检测结果:
// 修改检测顺序,把path放在最优先位置 const options = { order: ['path', 'localStorage', 'querystring', 'navigator',], // 新增path优先级最高 lookupQuerystring: 'lng', lookupCookie: 'i18next', lookupLocalStorage: 'i18nextLng', lookupSessionStorage: 'i18nextLng', lookupFromPathIndex: 0, // 取路径第一段作为locale 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: "en", // 原配置为ar,符合你默认语言为英语的需求可修改为此值 // 移除硬编码的lng: 'en'配置,避免覆盖路径检测结果 debug: true, whitelist: languages, checkWhitelist: true , detection: options, interpolation: { escapeValue: false, } });
2. 调整路由结构,统一增加locale前缀
你当前仅给编辑页配置了lng参数,需要把所有业务路由都包裹在/:lng前缀的父路由下,同时增加根路径自动重定向逻辑:
// react-router v5 示例 import { Switch, Route, Redirect } from 'react-router-dom' <Switch> {/* 所有业务路由都包裹在/:lng父路由下 */} <Route path="/:lng" render={(routeProps) => { // 校验locale合法性,不合法则跳转到默认语言路径 if (!['en','es','ar'].includes(routeProps.match.params.lng)) { return <Redirect to="/en" /> } return <MainLayout> <Route exact path="/:lng/services/edit" component={ServicesEdit} /> {/* 其他业务路由统一放在此处 */} </MainLayout> }} /> {/* 根路径自动重定向到默认语言路径 */} <Redirect from="/" to="/en" /> </Switch>
对应修改MenuContent中的跳转路径:
<Menu.Item key="2" icon={<UserOutlined />}> <Link to={`/${lng}/services/edit`}>{props.t("SERVICES_EDIT_PAGE")}</Link> </Menu.Item>
3. 修改语言切换函数,同步更新URL
原有切换逻辑仅修改i18n实例语言,没有同步更新路由,需要新增路径替换逻辑:
// 引入路由跳转能力,react-router v6用useNavigate,v5用useHistory import { useNavigate } from 'react-router-dom' // 组件内 const navigate = useNavigate() let handleClick = (newLng) => { i18n.changeLanguage(newLng) // 替换路径中的旧locale const pathSegments = window.location.pathname.split('/') if (['en','es','ar'].includes(pathSegments[1])) { pathSegments[1] = newLng } else { pathSegments.splice(1, 0, newLng) } navigate(pathSegments.join('/')) }
内容的提问来源于stack exchange,提问作者user16050054
相关产品推荐
相关产品推荐

