ReactJS和复杂的JSON对象

 hhxsv5 发布于 2023-01-19 11:06

我遵循了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 (
        
  • You have {this.state.data.notificationCount} notifications
  • ); } }); var Notifications = React.createClass({ render: function() { var notificationNodes = this.props.data.map(function (notif, index) { return {notif.type}; }); return
  • {notificationNodes}
  • ; } }); var Notification = React.createClass({ render: function() { return ( {this.props.children} 1 min ); } }); React.renderComponent( , 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验证).

    任何帮助都会很棒.

    非常感谢.

    1 个回答
    • 当你的组件首次渲染时,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>;
      }
      

      2023-01-19 11:07 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    热门标签
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有