【问题标题】:How to map a nested data object in React?如何在 React 中映射嵌套数据对象?
【发布时间】:2021-10-10 12:52:21
【问题描述】:

如何进一步访问此对象数组中的“名称”和“描述”?例如,我的目标是呈现两个按钮,分别是 Term 1 和 Term 2?我将有 3 张幻灯片,每张都有不同的术语/定义。所以我考虑制作一个组件,在那里我可以通过 props 传递一个索引,该索引引用要渲染的术语集。因此,每张幻灯片都会显示一组不同的术语名称和定义。

const TermData = [
  {
    index: 1,
    slideTitle: "Key Terms (1 of 3)",
    terms: [
      {
        name: "Term 1",
        definition: "Definition 1",
      },
      {
        name: "Term 2 ",
        definition: " definition 2",
      },
    ],
  },
  {
    index: 2,
    slideTitle: "Key Terms (2 of 3)",
    terms: [
      {
        name: "Term 1",
        definition: "Definition 1",
      },
      {
        name: "Term 2 ",
        definition: " definition 2",
      },
    ],
  },
];

//MAP THROUGH THE DATA - RENDER THE BUTTONS WITH TERM1 and TERM2 TITLE//
  const termSet = TermData.map((set, index) => {
    return (
      <>
        <button className="terms-button" key={index} onClick={() => handleClick(index)}>
          {set.terms[0].name}
        </button>
      </>
    );
  });
return (
    <Fragment>
        <div>
        {termSet}
        </div>
    </Fragment>
  );

【问题讨论】:

    标签: arrays reactjs object rendering array.prototype.map


    【解决方案1】:

    您必须将以下方法更改为

    //MAP THROUGH THE DATA - RENDER THE BUTTONS WITH TERM1 and TERM2 TITLE//
      const termSet = TermData[0].terms.map((set, index) => {
      return (
        <>
          <button className="terms-button" key={index}>
            {set.name}
          </button>
        </>
      );
    });
    

    Codesandbox这里

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 2021-03-29
      • 2018-04-02
      • 2021-12-11
      • 2021-06-23
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2016-05-19
      相关资源
      最近更新 更多