reactjs - useTranslation 在 react 钩子(Hook)中不起作用?

标签 reactjs react-hooks i18next

我有一个用 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;

文件仪表板.js:

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

最佳答案

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

关于reactjs - useTranslation 在 react 钩子(Hook)中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62210754/

相关文章:

reactjs - 类型错误 : __webpack_require__. i(...) 不是函数

javascript - 不将所有依赖项包含在 useEffect 依赖项数组中是不是一种反模式?

javascript - React 函数没有从功能组件传递到功能组件

reactjs - react-i18next 并用组件替换占位符键

javascript - 无法读取未定义的属性 'toResolveHierarchy'

javascript - 当我有 allMarkdownRemark 时, Gatsby 一直提示无法在类型 "fields"上查询字段 "MarkdownRemark"

javascript - reactjs中渲染方法内部的条件

reactjs - 使用 useTranslation() 中的 t() 时 react i18next "hooks"错误

reactjs - react native : TextInput toUpperCase does not work on Android in onChangeText

javascript - 如何在 Apollo Client React 中获取多个条件查询?