2015-10-06 69 views
0

在json feed中(下面)我有兩個數組,「rent」和「buy」我希望加入並顯示在html表中,但我不知道該在哪裏做。在反應中加入數組render render功能

飼料看起來像這樣...

"store": { 
       "rent": [ 
        { "title": "Lord of the ring masters", "cost": 2.99 } 
       ], 
       "buy": [ 
        { "title": "Fast and Furious 14", "cost": 5.99 }, 
        { "title": "Shogun Assassin", "cost": 2.99 } 
       ], 
       "total": 30.20 
      } 

而且在我看來,渲染功能,這將顯示上述的一個正確看起來像這樣

render: function(){ 

    var createRow = function(rowItem, i){ 
     return (
      <tr key={i}> 

       <td>{rowItem.name}</td> 
       <td>{rowItem.cost}</td> 
      </tr> 
     ); 
    }; 


    return (
     <div> 
      <h1>Package</h1> 
      <table className="table"> 
       <thead> 
       <th>Package</th> 
       <th>Name</th> 
       <th>Cost</th> 
       </thead> 
       <tbody> 
       {this.props.packageList.rent.map(createRow, this)} 
       </tbody> 
      </table> 
      Total: {this.props.packageList.total} 
     </div> 
    ); 
} 

可以在任何一個告訴我我如何改變上述加入陣列並呈現像這樣的數據...

**Rent** Lord of the ring masters £2.99 
**Buy** Fast and Furious 14 £5.99 
**Buy** Shogun Assassin £2.99 

回答

1

Rather比在渲染中調用地圖函數,在您的對象上創建另一個方法返回一個行數組。所以,你的新組件的樣子:

var myClass = React.createClass({  

renderRows: function() { 
    var rows = []; 
    this.props.packageList.rent.forEach(function(rowItem, i) { 
    rows.push(
     <tr key={i}> 
      <td>rent</td> 
      <td>{rowItem.name}</td> 
      <td>{rowItem.cost}</td> 
     </tr> 
    ); 
    }); 

    this.props.packageList.buy.forEach(function(rowItem, i) { 
    rows.push(
     <tr key={i}> 
      <td>buy</td> 
      <td>{rowItem.name}</td> 
      <td>{rowItem.cost}</td> 
     </tr> 
    ); 
    }); 
    return rows; 
}, 

render: function(){ 

return (
    <div> 
     <h1>Package</h1> 
     <table className="table"> 
      <thead> 
      <th>Package</th> 
      <th>Name</th> 
      <th>Cost</th> 
      </thead> 
      <tbody> 
      {this.renderRows()} 
      </tbody> 
     </table> 
     Total: {this.props.packageList.total} 
    </div> 
); 
} 

}) 

或者,你可以在數據提前結合的時間,只是做整個事情之一環。最後,您可能不希望在渲染函數中定義新函數,而是,正如我所建議的那樣,在該組件上創建一個新方法。另外,我還沒有測試過上述內容,所以一定要檢查錯誤。

+0

謝謝。它工作,但我不得不從每行刪除鍵,因爲它不會顯示所有的行。也許因爲重複? –

+0

從DOM:遇到兩個具有相同密鑰的孩子,'。$ 1'。子鑰匙必須是唯一的;當兩個孩子分享一把鑰匙時,只有第一個孩子會被使用 –

+0

好的 - 只需加上{key =「rent」+ i} –