i18next React - 更改语言仅在浏览器刷新后有效

i18next React - Changing language only works after browser refresh

在我的 React 页面上,更改语言仅在浏览器刷新后有效。已经尝试了以前帖子中所有可能的建议,但一无所获。它仅对 App.js 组件上的字符串按预期工作。任何帮助表示赞赏。

这是我的 i18n.js 文件

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

const resources = {
    'en': {translation: require('./translations/en.json')},
    'th': {translation: require('./translations/th.json')},
    'pt': {translation: require('./translations/pt.json')},
}

i18n
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    debug: true,
    fallbackLng: 'en',
    // lng: 'th',
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    resources
  });

export default i18n;

我的更改语言功能是这样的:

 handleLanguageChange = (item) => {
    i18n.changeLanguage(item.key, () => console.log('lanh1', i18next.language))
    // this.forceUpdate()
  }

正在 App.js 文件上导入:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import rootReducer from './store/reducers/rootReducer';
import thunk from 'redux-thunk';
import { applyMiddleware, createStore } from 'redux';
import { Provider } from 'react-redux';

import './i18n';

const store = createStore(rootReducer, applyMiddleware(thunk));

ReactDOM.render(
  <Provider store={store}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Provider>,
  document.getElementById('root')
);

reportWebVitals();

下面是我如何呈现翻译:

import React, { Component } from 'react';
import { Navigate} from "react-router-dom";

import { Button, Container, Grid } from '@mui/material';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { setCurRoute } from '../../store/actions/authAction';
import Background from '../../img/header-img.jpg';
import i18next from 'i18next';
// import i18n from '../../i18n';

class LandingPage extends Component {
  render() {
    return (
        <div
          style={{
          backgroundImage: `url(${Background})`,
          backgroundPosition: 'center',
          backgroundSize: 'cover',
          backgroundRepeat: 'no-repeat'
          }}
        >
          <h1 style={{textAlign: 'center'}}>{i18next.t('headline_one_one')}<br />{i18next.t('headline_one_two')}</h1>
          <h4 style={{textAlign: 'center', lineHeight: 2, border: '2'}}>
            {i18next.t('headline_two')}
          </h4>
        </div>
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LandingPage)

在 React 中,尝试使用 useTranslation hook or the withTranslation HOC。这将检测到语言变化。