问题
I'm new for i18next, trying to localize/translate website. Everything works for translation inside of component, but outside (means json files with i18n.t() it doesn't retrieve needed information, instead showing default value.
I'm using create-react-app and it's default settings for folders reference, maybe this is the key problem, but I can't find out why and what to change.
import i18n from '../../i18n';
const navigation = [
{
'id' : 'dashboard',
'title' : i18n.t('analytics.title', 'NOT FOUND'),
'type' : 'group',
'icon' : 'apps',
}
]
export default navigation;
And here is settings for i18n.js file:
import i18n from "i18next";
import Backend from 'i18next-xhr-backend';
import { initReactI18next } from 'react-i18next';
import detector from "i18next-browser-languagedetector";
i18n
.use(detector)
.use(Backend)
.use(initReactI18next)
.init({
lng: localStorage.getItem('language') || 'en',
backend: {
/* translation file path */
loadPath: '/assets/i18n/{{ns}}/{{lng}}.json'
},
fallbackLng: ['en', 'se', 'da'],
debug: true,
ns: ['translations'],
defaultNS: 'translations',
keySeparator: false,
interpolation: {
escapeValue: false,
formatSeparator: ','
},
react: {
wait: true
}
})
export default i18n;
and for index.js:
import 'typeface-muli';
import './react-table-defaults';
import './react-chartjs-2-defaults';
import { I18nextProvider } from "react-i18next";
import i18n from "./i18n";
import './styles/index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import App from 'app/App';
ReactDOM.render(
<I18nextProvider i18n={i18n}>
<App />
</ I18nextProvider>
,
document.getElementById('root'));
serviceWorker.unregister();
I'm just getting default : 'NOT FOUND'...
回答1:
You are using a backend service to fetch translations asynchronously in the browser. When importing i18n
you probably expected translation to be readily available, but that's not the case - i18n.init
is also an async method (if you try and await it, you'll be able to leverage t
function).
One possible approach would be defining a translation key:
const navigation = [
{
...
'title_key': 'analytics.title',
...
}
]
And later passing it down to t
within a component:
navigation.map(({ title_key }) => <li>t(title_key)</li>)
来源:https://stackoverflow.com/questions/57114733/i18next-translation-outside-component