I followed the ReactJS tutorial, which is pretty simple to do more complex things.
In my case, I would like to use a complex JSON object that contains a map, a single value, a list, etc. Here is the code:
var NotificationStatus = React.createClass({
loadNotificationsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
console.log(this.state.data.notificationType);
}.bind(this)
});
},
getInitialState: function() {
return {data: {}};
},
componentWillMount: function() {
this.loadNotificationsFromServer();
setInterval(this.loadNotificationsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div>
<li className="dropdown-menu-title">
<span>You have {this.state.data.notificationCount} notifications</span>
</li>
<Notifications data={this.state.data.notificationType} />
</div>
);
}
});
var Notifications = React.createClass({
render: function() {
var notificationNodes = this.props.data.map(function (notif, index) {
return <Notification key={index}>{notif.type}</Notification>;
});
return <li>{notificationNodes}</li>;
}
});
var Notification = React.createClass({
render: function() {
return (
<a href="#">
<span className="icon blue"><i className={this.props.children == "user" ? 'icon-user' : 'icon-comment-alt'}></i></span>
<span className="message">{this.props.children}</span>
<span className="time">1 min</span>
</a>
);
}
});
React.renderComponent(
<NotificationStatus url="/data/notifications.json" pollInterval={2000} />,
document.getElementById('notificationbar')
);
And this is a sample from JSON:
{
"notificationCount": "1",
"notificationType": [
{
"type": "update",
"text": "New Update"
},
{
"type": "user",
"text": "New User"
}
]
}
When I try to get notificationType, at this moment the error "this.props.data is undefined" occurs
var notificationNodes = this.props.data.map(function (notif, index) {
I really don't see what is wrong with the declaration, and when I get JSON at the ajax level, I have a map (verified using console.log).
Any help would be great.
Many thanks.
source
share