2017-05-29 66 views
0

我知道要做出反應,似乎無法通過這段代碼。我有一些我想輸出到dom的數據,但我不確定如何去做。誰能幫忙?在反應中輸出對象數組的正確方法是什麼?

的樣本數據: App.js:

 constructor(props){ 
     super(props); 
     this.state.foods = [ 
     { 
     recipe: '1 cup egg, 4 cups...', 
     time: 42 
     }, 
     { 
     recipe: '1 tbsp butter, 2 cups...', 
     time: 120 
     } 
     ] 
     } 
    `render(){ 
    <div className='App'> 
     <Recipes data={this.state.foods} /> 
    </div> 
` 

我將如何正確去在我的食譜分量輸出呢?我已經嘗試過對this.props.foods數組的內容進行forEach循環,但無法使其工作,任何幫助都會很棒。

The output I would like to see is: 

    <H2> 1 cup egg, 4 cups...</h2> 
    <h3> Time: 42 minutes </h2> 
    <br> 
    <H2> 1 tbsp butter, 2 cups...</h2> 
    <h3> Time: 120 minutes </h2> 

回答

0

使用Array.prototype.map(),如:

{this.props.data.map(food => <div> 
    <h2>{food.recipe}</h2> 
    <h3>Time: {food.time} minute{food.time !== 1 ? 's' : ''}</h3> 
</div>} 
0

想法的方式是利用地圖作爲@Jonny還建議,然而,只要你映射了一個數組,你應該加入他的回答指定生成的JSX元素的鍵。它有助於提高反應的性能,因爲React通過鍵標識了變化,如果鍵是相同的,則元素不會重新渲染。

想法鍵是索引以外的唯一屬性,因爲如果從數組中間刪除項目,索引可能會更改。但是,如果沒有其他選項可用,你也可以使用它

{this.props.data.map((food, index) => <div key={index}> 
    <h2>{food.recipe}</h2> 
    <h3>Time: {food.time} minute{food.time !== 1 ? 's' : ''}</h3> 
</div>} 
相關問題