ReactJS和复杂的JSON对象

4

我跟随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"
       }
     ]
    }

当我尝试获取通知类型时,此处会引发错误“this.props.data未定义”。
    var notificationNodes = this.props.data.map(function (notif, index) {

我真的看不出声明有什么问题,当我在ajax层获取JSON时,确实有一个映射表(通过console.log验证)。

任何帮助都将是极好的。

非常感谢。

2个回答

9
当您的组件首次呈现时,NotificationStatus 的 this.state.data 将是 {},因为它是从 getInitialState 返回的内容。这意味着当您进行渲染时,要注意此状态可能为空。
<Notifications data={this.state.data.notificationType} />

您正在传递{}.notificationTypeundefined

<Notifications data={undefined} />

当通知首次渲染时,this.props.data不是一个列表。这取决于您的应用程序,正确的修复方法可能是,您希望使用data: null进行初始化,并将其添加到NotificationStatus的render方法的顶部:

if (!this.state.data) {
    return <div>Loading...</div>;
}

3
除了Ben提到的问题,你还在componentWillMount中调用loadNotificationsFromServer。你应该在componentDidMount内调用loadNotificationsFromServer并启动任何计时器,因为你的组件尚未安装在DOM中。你可以在此处阅读更多信息: React Component Lifecycle 回顾代码,我不确定你的对象图应该是什么样子的,但在一个地方,它看起来像你正在尝试迭代一组通知,而在另一个地方,是单个通知。
为了缓解Ben提到的问题,你还可以使用逻辑运算符来初始化你的状态,通过默认值来设置notificationType和count(''和0)作为快速修复。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接