2016-02-04 69 views
1

我有一个包含几个停车库信息的Json字典文件。车库名称是该车库的详细信息的关键。 the data structure is like this如何通过React按键返回对象内容(JSON文件)?

我正在尝试在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并运行用于循环内,并且调用Mycomponent.Garage该车库的每个细节的信息。

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

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

感谢

回答

1

使用在循环您的收益将无法正常工作,但你接近得到它的权利!相反,尝试创建一个车库节点阵列:

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; 
    } 
});