英文:
useTranslation not working in react/typescript
问题
I have a project write with react/typescript and I want to change language. I use i18n but when I use useTranslation to change language it doesn't work.
packages:
"i18next": "22.4.9",
"react-i18next": "12.1.4"
i18n -> config.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n.use(initReactI18next).init({
fallbackLng: 'en',
lng: 'en',
resources: {
en: {
translations: require('./locales/en/translations.json')
}
},
ns: ['translations'],
defaultNS: 'translations'
});
i18n.languages = ['en'];
export default i18n;
i18n -> locales -> en -> translations.json
{
"errorMessage": "Please try again later."
}
App.tsx
import { useTranslation } from 'react-i18next';
const App = () => {
const { t } = useTranslation();
return (<>
{t('errorMessage')}
</>)
}
export default App
On running, I see this:
errorMessage
instead of
Please try again later.
What am I missing?
英文:
I have a project write with react/typescript and I want to change language. I use i18n but when i use useTranslation to change language it doesn't work.
packages:
"i18next": "22.4.9",
"react-i18next": "12.1.4"
i18n -> config.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n.use(initReactI18next).init({
fallbackLng: 'en',
lng: 'en',
resources: {
en: {
translations: require('./locales/en/translations.json')
}
},
ns: ['translations'],
defaultNS: 'translations'
});
i18n.languages = ['en'];
export default i18n;
i18n -> locales -> en -> translations.json
{
"errorMessage": "Please try again later."
}
App.tsx
import { useTranslation } from 'react-i18next';
const App = () => {
const { t } = useTranslation();
return (<>
{t('errorMessage')}
</>)
}
export default App
On running, I see this:
> errorMessage
instead of
> Please try again later.
What am I missing?
答案1
得分: 1
You have to import the config.js file preferably in App.tsx file since it has to be bundled.
import './i18n/config';
英文:
You have to import the config.js file preferably in App.tsx file since it has to be bundled.
import './i18n/config';
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论