麻烦在ReactJs上迭代数组

时间:2015-09-24 12:59:45

标签: javascript arrays reactjs

我正在尝试遍历这个数组:

events: [{
      "id": "123",
      "key": "1",
      "type": "academic",
      "time": "2015 - 2016",
      "title": " MSc in Software Engineering",
      "place": "University of Oxford",
      "location": "Oxford, United Kingdom",
      "description": "Lorem impsum",
      "gallery": []
    },
    {
      "id": "234",
      "key": "2",
      "type": "professional",
      "time": "2015 - 2016",
      "title": " Software Engineer",
      "place": "University of Oxford",
      "location": "Oxford, United Kingdom",
      "description": "Lorem impsum",
      "gallery": [
        {
          "index": 11,
          "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash2/v/t1.0-1/p160x160/10923196_10204583699694173_6145976884213630323_n.jpg?oh=bd235908314ecf0ab5afa8d3f92f5abf&oe=567B51F9&__gda__=1450897067_285c7c8c720c0f130453b37e9ff9b2f8"
        }
      ]
    },
    {
      "id": "567",
      "key": "3",
      "type": "misc",
      "time": "2015 - 2016",
      "title": " MSc Software Engineering",
      "place": "University of Oxford",
      "location": "Oxford, United Kingdom",
      "description": "Lorem impsum",
      "gallery": [
            {
          "index": 1,
          "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash2/v/t1.0-1/p160x160/10923196_10204583699694173_6145976884213630323_n.jpg?oh=bd235908314ecf0ab5afa8d3f92f5abf&oe=567B51F9&__gda__=1450897067_285c7c8c720c0f130453b37e9ff9b2f8"
        }
      ]
    }
  ]

我的代码:

events.map(( timelineEvent ) => {
      let directions;
      if (timelineEvent % 2 == 0) {
        directions = "direction-r";
      } else {
        directions = "direction-l"
      }
      return (
        <li key={timelineEvent.id}>
          <TimelineEvent 
            type = {timelineEvent.type}
            time = {timelineEvent.time}
            title = {timelineEvent.title}
            place = {timelineEvent.place}
            location = {timelineEvent.location}
            description = {timelineEvent.description}
            direction = {directions}>
            <div>gallery</div>
            <TimelineEditButton
              deleteClick={timelineEvent.id} 
              dataId={ timelineEvent.id}
              editClick={this.openPartial.bind(this, "editEventPartial")} />
          </TimelineEvent>
        </li>
      );
    });

但是收到以下错误:

Error: Invariant Violation: Objects are not valid as a React child (found object with keys {id, key, type, time, title, place, location, description, gallery}). If you meant to render a collection of children, use an array instead or wrap the object using React.addons.createFragment(object).

由于我是React的新手,我无法弄清楚是什么导致了这种情况。我使用的是React 0.14-rc1。

有人可以指出问题吗?感谢

1 个答案:

答案 0 :(得分:1)

您使用过timelineEvent % 2 == 0,也许这就是问题所在?由于timelineEvent是一个对象,我猜你想在“索引”或timelineEvent.id而不是整个对象上这样做。