我们如何在i18next配置中使用react查询

问题描述 投票:0回答:1

我正在使用 i18next 库在我的 React 应用程序中实现本地化,我必须调用 API 来在响应中获取本地化信息。但是我想使用react query来调用API,并且我知道react query作为一个钩子只能在功能组件中调用,所以我无法使用react query。有人遇到过这个错误吗?

我的i18next配置。

export const getLocalisation = async (lng: string) => {
    try {
        const localisationResponse = await axios.get(
            `/localisation/${lng}`
        );
        return localisationResponse;
    } catch (err) {
        console.log('Error at getLocalisation: ', err);
    }
};
const backendOptions = {
    allowMultiLoading: true,
    loadPath: `/localisation/en`,
    request: (options: any, url: any, payload: any, callback: any) => {
        try {
            getLocalisation(EN).then((result) => {
                callback(null, {
                    data: result?.data,
                    status: STATUS_CODE_200
                });
            });
        } catch (e) {
            console.error(e);
            callback(e); // Passing `e` will handle error status code
        }
    }
};

i18n
    .use(HttpBackend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        debug: false,
        fallbackLng: EN,
        supportedLngs: [EN],
        ns: [],
        partialBundledLanguages: true,
        interpolation: {
            escapeValue: false
        },
        backend: backendOptions
    });

export default i18n;

使用反应查询时,收到以下错误/警告。 enter image description here

reactjs i18next react-query i18next-http-backend
1个回答
0
投票

你可以这样做:

import i18n from "i18next";
import { useCallback, useLayoutEffect } from "react";
import { initReactI18next } from "react-i18next";
import { useI18nQuery } from "../hooks/useApiQueries";
import { APP_LANGUAGE_DEFAULT, APP_LANGUAGE_SUPPORTS } from "../utils/const";

i18n
  .use(initReactI18next)
  .init({
    partialBundledLanguages: true,
    interpolation: {
      escapeValue: false
    },
    fallbackLng: APP_LANGUAGE_DEFAULT, // 'en'
    supportedLngs: APP_LANGUAGE_SUPPORTS,  // ['en', 'de']
    ns: [],
    resources: {}
});

const AppTranslation: React.FC<{lang?: string, children?: React.ReactNode;}> = ({ lang, children }) => {
  
  const _lang = lang || 'en';
  const i18nQuery = useI18nQuery( _lang );

  const initLang = useCallback(() => {

    if( !i18nQuery.data ) return;

    i18n.addResourceBundle('de', 'app', i18nQuery.data.de);
    i18n.addResourceBundle('en', 'app', i18nQuery.data.en);
    i18n.setDefaultNamespace('app');

  }, [ i18nQuery.data ])

  const removeLang = useCallback(() => {

    if( !i18nQuery.data ) return;
    
    i18n.removeResourceBundle('de', 'app');
    i18n.removeResourceBundle('en', 'app');
    
  }, [ i18nQuery.data ])

  useLayoutEffect(() => {
    initLang();
    return () => {
      removeLang()
    };
  }, [ i18nQuery.isLoading ]);
  
  return children;
}

export default AppTranslation;

然后在您的索引或加载应用程序组件的位置:

...
<QueryClientProvider client={queryClient}>
  <AppTranslation />
  <App />
</QueryClientProvider>
...

然后你就可以使用

const { t } = useTranslation()

钩在你想要的地方。

© www.soinside.com 2019 - 2024. All rights reserved.