2016-02-04 67 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; 
    } 
});