循环嵌套的对象数组,渲染不同的标记

时间:2018-02-05 21:23:00

标签: javascript reactjs ecmascript-6 reduce

我用React应用程序打了一个兔子洞。我looping通过这个对象数组:

const weeklyClasses = [
  {
    id: 1,
    day: "Monday",
    classDescription: [
      { classType: "11am-12pm Jazz", teacher: "Joe" },
      { classType: "1pm-2pm Blues", teacher: "Doe" },
      { classType: "3pm-4pm Samba", teacher: "Zen" }
    ]
  },
  {
    id: 1,
    day: "Tuesday",
    classDescription: [
      { classType: "11am-12pm Rock", teacher: "Sis" },
      { classType: "1pm-2pm Tango", teacher: "Ter" },
      { classType: "3pm-4pm Salsa", teacher: "Soul" }
    ]
  },
  // ...
];

我正在循环并检索所需的值,但是,目前classType输出为p

const Data = () => {
  return weeklyClasses.map((o, i) => {
    return (
      <div className="classDay" key={o.id}>
        {o.day}
        <div className="classType">
          {o.classType}
          //Right here
          <p>{o.classDescription.map(i => i.classType)}</p>
        </div>
      </div>
    );
  });
};

如何将每个 classType输出为 diff p标签?

在地图上映射是否可以? (我应该怎样才能使用reduce?)

regex demo

1 个答案:

答案 0 :(得分:7)

而不是将整个描述数组包装成单个p

<p>{o.classDescription.map(i => i.classType)}</p>

您可以将每个类描述元素包装成p而不是:

{o.classDescription.map(i => <p>{i.classType}</p> )}
{/*                          ^^^             ^^^^  */}