首页 > 解决方案 > useTranslation 在反应钩子中不起作用?

问题描述

我有一个使用反应钩子编写的项目,我想更改语言。我使用 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;

文件仪表板.js:

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

标签: reactjsreact-hooksi18next

解决方案


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


推荐阅读