我在弄清楚如何使用 i18next 延遲加載我的翻譯時遇到問題。
這是我的設定:
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
debug: NODE_ENV === 'development',
defaultNS: 'translation',
fallbackLng: false,
fallbackNS: 'translation',
keySeparator: false,
lng: 'en',
load: 'currentOnly',
nsSeparator: '.'
});
我有一個這樣的檔案夾結構:
├── src
│ └── pages
│ ├── customer
│ │ └── home.tsx
│ └── manager
│ └── dashboard.tsx
我保留我的翻譯/public/locales/en/translation.json,這很好用。但是,我的應用程式正在擴展,我不想將我所有的語言翻譯保存在單個檔案中。例如,customer不需要下載manager門戶網站上發生的事情的所有翻譯。
我的目標是專門為經理的儀表板下載翻譯。
我嘗試創建一個檔案并將其添加到此位置
/public/locales/en/manager/dashboard
然后在我的 React 組件中,我使用了以下鉤子:
...
// This probably needs to change
const { t } = useTranslation('manager.dashboard');
return <div>{t('Hello World')}</div>
只是為了測驗它/public/locales/en/manager/dashboard.json(我真的想維護這個檔案結構)檔案中有一個鍵值:
{ "Hello World": "Goodbye World" }
它不起作用(如果我將此密鑰添加到/public/locales/en/translation.json檔案中則有效)
如何更改我的配置以使這種有組織的嵌套翻譯檔案結構正常作業。
uj5u.com熱心網友回復:
如果您像這樣使用 useTranslation:
const { t } = useTranslation('manager.dashboard');
你的檔案名應該是這樣的 /public/locales/en/manager.dashboard.json
順便提一句。延遲加載時,請確保使用 Suspense 或檢查就緒標志:https ://react.i18next.com/latest/usetranslation-hook#not-using-suspense
您還可以查看此頁面,了解多個翻譯檔案:https ://react.i18next.com/guides/multiple-translation-files
編輯:或者,你可以試試這個:
const { t } = useTranslation('manager/dashboard');
像這里:https ://codesandbox.io/s/react-i18next-http-example-forked-2ptmu?file=/src/app.js:153-162
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/415575.html
標籤:
