【问题标题】:useTranslation not working in react hook?useTranslation 在反应钩子中不起作用?
【发布时间】:2020-09-24 09:20:53
【问题描述】:

我有一个使用 react hook 编写的项目,我想更改语言。我使用 i18n,但是当我使用 useTranslation 更改语言时,它会加载很长时间,我不知道如何修复它。请帮我解决这个问题,对不起我的英语不好。

文件路径:

const Routes = () => {
  return (
    <Suspense fallback={<BrandLoading />}>
      <Switch>
        <RouteWithLayout
          component={DashboardView}
          exact
          layout={MainLayout}
          path={`/${routeUrls.dashboard.path}`}
        />
      </Switch>
    </Suspense>
  );
};

export default Routes;

文件 App.js

import React from 'react';
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import { ThemeProvider } from '@material-ui/styles';
import theme from 'theme';
import Routes from 'routes';
import './i18n'

const browserHistory = createBrowserHistory();
const App = () => {
  return (
    <ThemeProvider theme={theme}>
      <Router history={browserHistory}>
        <Routes/>
      </Router>
    </ThemeProvider>
  );
};

export default App;

文件 i18n.js:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n.use(LanguageDetector)
    .use(initReactI18next)
    .init({
     defaultNS: 'translation',
     fallbackLng: 'vn',
     debug: true,
     interpolation: {
       escapeValue: false, 
     },
     load: 'languageOnly',
     saveMissing: true,
   });
export default i18n;

文件dashboard.js:

const Dashboard = ({ className = '' }) => {
  const { t, i18n } = useTranslation();
  return (
    <div>
      <Typography>{t.hello}</Typography>
    </div>
  );
};
export default Dashboard;

【问题讨论】:

    标签: reactjs react-hooks i18next


    【解决方案1】:

    它应该是t('hello') 而不是t.hello,因为t 是一个函数,而不是一个对象

    【讨论】:

      【解决方案2】:

      看看这里的文档是个好主意: https://react.i18next.com/latest/usetranslation-hook

      您还需要在 i18n.js 中处理您的翻译文件

      【讨论】:

        猜你喜欢
        • 2021-04-10
        • 2019-08-06
        • 2022-10-21
        • 2021-12-15
        • 2021-10-15
        • 2021-01-10
        • 2021-10-16
        • 2021-03-24
        • 2019-10-09
        相关资源
        最近更新 更多