【发布时间】:2014-04-12 06:47:38
【问题描述】:
我遵循了 ReactJS 教程,这很容易完成更复杂的事情。
在我的例子中,我想使用一个复杂的 JSON 对象,它包含一个映射、一个单一的值、一个列表等......这是代码:
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')
);
这是来自 JSON 的示例:
{
"notificationCount": "1",
"notificationType": [
{
"type": "update",
"text": "New Update"
},
{
"type": "user",
"text": "New User"
}
]
}
当我尝试获取 notificationType 时,此时会出现错误“this.props.data is undefined”
var notificationNodes = this.props.data.map(function (notif, index) {
我真的看不出声明有什么问题,当我在 ajax 级别获取 JSON 时,我确实有一张地图(通过 console.log 验证)。
任何帮助都会很棒。
非常感谢。
【问题讨论】:
标签: javascript json reactjs