您好,选择新语言后,我无法更改 href 路径 (URL)
import i18n from 'i18next';
import { useTranslation, initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import I18NextHttpBackend from 'i18next-http-backend';
i18n.on('languageChanged', function (lng) {
if (lng === i18n.options.fallbackLng[0]) {
if (window.location.pathname.includes('/' + i18n.options.fallbackLng[0])) {
const newUrl = window.location.pathname.replace(
'/' + i18n.options.fallbackLng[0]
);
window.location.replace(newUrl);
}
}
});
i18n
.use(I18NextHttpBackend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: ['en'],
whitelist: ['en', 'de', 'it', 'es'],
detection: {
order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'],
caches: ['cookie'],
lookupFromPathIndex: 0,
checkWhitelist: true,
},
backend: {
loadPath: '/localization/{{lng}}/translation.json',
},
interpolation: {
escapeValue: false,
},
});
export default i18n;
我得到了 example.com/undefined/page1
我用这种方式将语言路径导入到 Href
export const baseUrl = i18n.language === 'en' ? '' : '/' + i18n.language;
和链接<a>home</a>
<a className='item' href={baseUrl + '/'} > Home </a>