2017-02-12 139 views
0

我有一個簡單的組件Movies.jsx和movieList.jsx內的對象數組我導出這個數組並設置Movies.jsx內的狀態等於該數組。當我看着控制檯時,我發現它已經傳遞到狀態正常。迭代通過數組和渲染

我想遍歷該對象數組並渲染它:我該怎麼做? 無論我嘗試我得到一個錯誤「對象不是有效的作爲一個React的孩子」

在我把它變成數組之前,它是一個json對象,但我沒有看過。

我也得到一個錯誤,「在一個數組或迭代每個孩子都應該有一個獨特的‘鑰匙’託」

enter image description here

enter image description here

例2: 它怎麼會是如果不是數組,它是JSON對象。我們是否也需要將它從單獨的組件導出然後需要?我們將如何迭代它?

enter image description here

回答

2

下面是您試圖實現的一個簡單示例。既然你提供了截圖,我不得不提供轉換數據。

var Movies = { 
 
    "data": [{ 
 
     "id": 1, 
 
     "name": "Forest Gump", 
 
     "rating": 5 
 
    }, { 
 
     "id": 2, 
 
     "name": "Lion", 
 
     "rating": 5 
 
    }] 
 
}; 
 

 
var Movie = React.createClass({ 
 
    render: function() { 
 
    return (
 
     <div> 
 
      <div>Name: {this.props.item.name}</div> 
 
      <div>Rating: {this.props.item.rating}</div> 
 
     </div> 
 
    ); 
 
    } 
 
}); 
 

 
var MovieContainer = React.createClass({ 
 
    getInitialState() { 
 
    return { 
 
     movies: null 
 
    }; 
 
    }, 
 
    componentWillMount: function() { 
 
    this.setState({ 
 
     movies: Movies.data 
 
    }) 
 
    }, 
 
    render: function() { 
 
    return (
 
     <div> 
 
     { this.state.movies.map(function(item) { 
 
      return (
 
      <Movie key={item.id} item={ item } /> 
 
     ) 
 
     }) } 
 
     </div> 
 
    ); 
 
    } 
 
}); 
 
    
 
ReactDOM.render(
 
    <MovieContainer />, 
 
    document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script> 
 

 
<div id="container"></div>

+0

謝謝你贏。這很漂亮。你可以請更新答案,並告訴我,而不是提供的數組,它是有問題的JSON對象。也在一個單獨的組件。示例在我的問題上面。我是否也需要將其導出或需要足夠的空間。 –

+0

@ Igor-Vuk更新了我的回答。 – Win