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

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

我几乎尝试了 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;

演示.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
用于加载翻译。

需要注意的是:我发现这 3 个链接对我没有帮助。

locales
位于我的公共文件夹中
public\locales\{lng}.json

从昨天开始我就找不到任何方法来解决这个问题。而且,这让我很困惑!

请帮助我!

reactjs axios i18next react-i18next
1个回答
0
投票

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;

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