2016-07-21 68 views
1

我有一個對象數組。使用地圖來創建HTML ReactJS

notifications = [ 
{notification:"this is notification1"}, 
{notification:"this is notification2"}, 
{notification:"this is notification3"}, 
] 

我一直試圖通過數組映射並創建HTML代碼。

return (
     <div> 
     {notifications.map(function(notificationItem) { 
     <a> {notificationItem.notification} </a> 
     })} 
     </div> 
    ); 

有人能告訴我這是什麼錯誤嗎?

謝謝!

回答

3

.map你應該返回值 - 。添加return語句.map,也是在這種情況下,你應該增加key財產的每個元素,因爲子元素應該有獨特的按鍵,你可以閱讀更多有關和解here

var App = React.createClass({ 
 
    render: function() { 
 
    const notifications = this.props.notifications 
 
     .map(function(notificationItem, index) { 
 
     return <a key={index}> {notificationItem.notification} </a>; 
 
     }); 
 

 
    return <div>{ notifications }</div>; 
 
    } 
 
}); 
 

 
var notifications = [ 
 
    {notification:"this is notification1"}, 
 
    {notification:"this is notification2"}, 
 
    {notification:"this is notification3"}, 
 
]; 
 

 
ReactDOM.render(
 
    <App notifications={ notifications } />, 
 
    document.getElementById('container') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="container"></div>

+1

非常感謝你 –

1

我還想補充一點,如果你不需要有狀態的反應,你也可以寫你的組件在這種風格:

const notifications = [ 
    { notification: "1" }, 
    { notification: "2" }, 
    { notification: "3" }, 
]; 

const App = function({ notifications }) { 
    return (
    <div> 
     { 
     notifications.map((item, index) => <a key={index}>{item.notification}</a>) 
     } 
    </div> 
) 
} 

ReactDOM.render(
    <App notifications={ notifications } />, 
    document.getElementById("app") 
) 
+0

我的代碼非常複雜。我剛剛發佈了一個示例代碼 –