如何通过React按键返回对象内容(JSON文件)?

时间:2016-02-04 18:00:52

标签: javascript html dom reactjs

我有一个包含几个停车库信息的Json字典文件。车库名称是该车库详细信息的关键。 the data structure is like this

我正在尝试在React中编写一个for循环,以列表格式将所有车库信息提取到我的网页。

我的代码:

MyComponents.Garage = React.createClass({
  render: function() {
    var garage = this.props.garage
     console.log(garage)
    return (
        <li className="card-content">
        TODO: This is a component about a garage whose
        raw data is //{JSON.stringify(this.props.garage)}
          <MyComponents.GarageTitle
            title={this.props.garage.friendlyName}/>
          <MyComponents.GarageSpaces
            open={this.props.garage.open_spaces}
            total={this.props.garage.total_spaces}/>
          <MyComponents.GarageRates
            rates={this.props.garage.rates}/>
          <MyComponents.GarageHours
            hours={this.props.garage.hours}/>
        </li>
    );
  }
});
MyComponents.Garages = React.createClass({
  render: function(){
    console.log(this.props.garage)
    for (var key in this.props.garage){
      console.log(this.props.garage[key])
      return (
        <ul>
        <MyComponents.Garage garage={this.props.garage[key]}/>
        </ul>
      );
    }
  }
});

我首先将Json数据传递给Mycomponent.Garages并在其中运行for循环,并为该Garage的每个详细信息调用Mycomponent.Garage。

但我的问题是我只能穿过第一个车库,它不会继续循环剩下的车库。

任何人都可以帮我完成任务吗?

由于

1 个答案:

答案 0 :(得分:1)

在for for循环中使用return不起作用,但你已经接近正确了!相反,尝试创建一个车库节点数组:

MyComponents.Garages = React.createClass({
  render: function(){
    garageNodes = [];
    for (var key in this.props.garage){
      console.log(this.props.garage[key])
      garageNodes.push(
        <ul>
          <MyComponents.Garage garage={this.props.garage[key]}/>
        </ul>
      );
    }
  return garageNodes;
  }
});