我遵循了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 (); } }); var Notifications = React.createClass({ render: function() { var notificationNodes = this.props.data.map(function (notif, index) { returnYou have {this.state.data.notificationCount} notifications {notif.type} ; }); return
这是来自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验证).
任何帮助都会很棒.
非常感谢.
当你的组件首次渲染时,NotificationStatus this.state.data
将是{}
因为那是从中返回的getInitialState
.这意味着当你渲染
<Notifications data={this.state.data.notificationType} />
你正在经过{}.notificationType
或undefined
:
<Notifications data={undefined} />
因此,当通知首次呈现时,this.props.data不是列表.这取决于你的应用程序在这里正确修复了什么,但也许你想初始化data: null
并将其添加到NotificationStatus的render方法的顶部:
if (!this.state.data) { return <div>Loading...</div>; }