如何在react中使用i18next通过axios翻译REST API内容?

mbzjlibv  于 11个月前  发布在  iOS
关注(0)|答案(1)|浏览(113)

几乎我尝试了在Stackoverflow上找到的每一个解决方案,这些解决方案对我来说都不起作用。
我尝试在获取数据后翻译REST API内容。
下面是一些片段:

i18n.js:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";
import axios from "axios";

const loadResources = async (locale) => {
  return await axios
    .get("https://jsonplaceholder.typicode.com/posts", {
      params: { lang: locale },
    })
    .then((res) => {
      return res.data.slice(0, 3);
    })
    .catch((err) => {
      console.log(err);
    });
};

const detectorOptions = {
  order: ["cookie", "localStorage", "navigator"],

  lookupCookie: "locales",
  lookupLocalStorage: "locales",

  caches: ["localStorage", "cookie"],
  excludeCacheFor: ["cimode"],
  checkWhiteList: true,
};

const backendOptions = {
  loadPath: "/locales/{{lng}}/{{ns}}.json", //used to pass language and namespace to custom XHR function
  request: (options, url, payload, callback) => {
    try {
      const [lng] = url.split("|");

      loadResources(lng).then((data) => {
        callback(null, {
          data: JSON.stringify(data),
          status: 200, //status code is required by XHR plugin to determine success or failure
        });
      });
    } catch (e) {
      console.error(e);
      callback(null, {
        status: 500,
      });
    }
  },
};

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    debug: true,
    fallbackLng: "en",
    backend: {
      loadPath: "/locales/{{lng}}/{{ns}}",
    },
    detection: detectorOptions,
    whitelist: ["en", "zh", "jp", "fr"],
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

字符串

Demo.js

import { useTranslation } from "react-i18next";
import axios from "axios";
import { useEffect, useState } from "react";

export default function Demo() {
  const { t } = useTranslation();
  const [data, setData] = useState([]);

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then((res) => {
        setData(res.data.slice(0, 3));
      })
      .catch((err) => {
        console.log(err);
      });
}, [data]);

return (
    <>
    <section>
        {data.map((i, index) => {
          return (
            <>
              <div key={index}>
                <h4>{i.title}</h4>
                <p>{i.body}</p>
              </div>
            </>
          );
        })}
      </section>
   </>
)


我不知道如何使用Axios从REST API内容加载翻译。但我知道i18next-http-backend用于加载翻译。
注意:我发现这三个链接对我没有帮助。

locales位于我的公用文件夹public\locales\{lng}.json
另外,我发现这个github问题的链接是断开的:(
i18next-http-backend github issue
从昨天开始我就找不到解决这个问题的方法。而且,这让我很困惑!
请帮帮我!

0qx6xfy6

0qx6xfy61#

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useTranslation } from 'react-i18next';

const YourComponent = () => {
  const { t } = useTranslation();
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('YOUR_API_ENDPOINT');
        // Assuming your API response has a field 'content' to be translated
        const translatedData = {
          ...response.data,
          content: t(response.data.content),
        };
        setData(translatedData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [t]);

  if (!data) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <p>{data.content}</p>
      {/* Render other translated content */}
    </div>
  );
};

// LanguageSwitcher.jsx

import React from 'react';
import { useTranslation } from 'react-i18next';

const LanguageSwitcher = () => {
  const { i18n } = useTranslation();

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
  };

  return (
    <div>
      <button onClick={() => changeLanguage('en')}>English</button>
      <button onClick={() => changeLanguage('fr')}>French</button>
      {/* Add more language buttons as needed */}
    </div>
  );
};

export default LanguageSwitcher;

字符串

相关问题