如何使用 react-i18next 使用 .map() 转换对象数组中的数据

How to Translate data in array of objects with .map() using react-i18next

刚开始使用 i18next,在翻译以下数据时遇到了一些问题。

export const educationData = [
  { education: "Some education 1", timeframe: "2017 - 2018", id: 1 },
  { education: "Some education 2", timeframe: "2016 - 2017", id: 2 },
  { education: "Some education 3", timeframe: "2015 - 2016", id: 3 },
  { education: "Some education 4", timeframe: "2014 - 2015", id: 4 }
];

JSON 在不同语言的语言环境中看起来像:

"education": {
  "heading": "Education",
  "educationData": [
    {
      "id": 1,
      "education": "Some education 1",
      "timeframe": "2017 - 2018"
    },
    {
      "id": 2,
      "education": "Some education 2",
      "timeframe": "2016 - 2017"
    },
    {
      "id": 3,
      "education": "Some education 3",
      "timeframe": "2015 - 2016"
    },
    {
      "id": 4,
      "education": "Some education 4",
      "timeframe": "2014 - 2015"
    }
  ]
}

组件看起来像:

import React from "react";
import { useTranslation } from "react-i18next";
import { educationData } from "../data/educationData";
import Education from "./Education.js";

function ListEducation() {
  const { t } = useTranslation();
  return (
    <div className="education py-1">
      <h2>{t("education.heading")}</h2>
      <hr />
      {educationData.map((edu) => (
        <Education
          key={edu.id}
          education={edu.education}
          timeframe={edu.timeframe}
        />
      ))}
    </div>
  );
}

export default ListEducation;

如何让翻译在 .map() 函数中工作?在 .map() 之外,类似 t("education.educationData.0.education") 的东西工作正常。

在 .map 函数内部,它只是将 "education.educationData.0.education" 作为字符串输出。

你可以试试这个

{t(`education.educationData.${id}.${education}`)}

你基本上是在连接字符串。

您可以使用以下方式从带翻译的文件访问数组:

t('education.educationData', { returnObjects: true })

然后轻松映射通过这个数组。
资料来源:i18next documentation: Arrays