簡體   English   中英

使用React JS的組件“循環”

[英]Component “loop” with React JS

我正在研究React JS庫,我希望創建一個組件的“循環”,從json文件返回數組值。 這是我的json文件:

{
  "data": {
    "children": [{
      "data": {
        "score": 4
      },
      {
        "data": {
          "score": 2
        }
      }
    }]
  }
}

我的反應成分:

var ImagesList = React.createClass({
    render: function() {
      var imagesNodes = this.props.data.map(function (image){
        return (
          <div className="card">
              <p>{image.score} </p>
          </div>
        );
      });

      return (
        <div className="images">
          {imagesNodes}
        </div>
      );
    }
  });

var ImageBox = React.createClass({
    getInitialState: function(){
      return {
        data: {children:[]}
      };
    },

    getImages: function(){
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        success: function(data){
          this.setState({data: data});
        }.bind(this),
        error: function(xhr, status, err){
          console.error(url, status, err.toString());
        }.bind(this)
      });
    },

  componentWillMount: function(){
      this.getImages();
  },

  render: function() {
    return (
      <div className="list-images">
          {<ImagesList data={this.state.data.children}/>}
      </div>
    );
  }
});

  React.render(
    <ImageBox url="myfile.json" />,
    document.getElementById('test')
  );

當我運行代碼時,返回此錯誤:

Uncaught TypeError:無法讀取未定義的屬性“ map”。

我不知道該如何解決。

JSON輸入數據似乎無效。 JSONParser上進行了驗證

ImageList組件期望data對象內有children JSON Array。 因此,如果AJAX調用返回以下JSON,則組件將能夠呈現該數據

{
  "children": [
    {
      "score": 4
    },
    {
      "score": 2
    }
  ]
};

請注意, this.setState({data: data}); 已經具有data變量。 因此,響應不應再次設置data否則它將變為data.data.children 這就是代碼拋出Uncaught TypeError: Cannot read property 'map' of undefined.

為了在您完成ReactJS學習之后進一步閱讀,我建議檢查Flux Architecture ,這是實現ReactJS應用程序的推薦方法

讓我們調試您的代碼。 在代碼的ajax回調函數中。 您將獲得json數據返回,並使用返回數據設置狀態數據。 因此this.state.data將是:

{
  "data": {
    "children": [{
      "data": {
        "score": 4
      },
      {
        "data": {
          "score": 2
        }
      }
    }]
  }
}

並且在render方法中,您嘗試將props從ImageBox插入到ImagesList中,如下所示:

data = { this.state.data.children }

但是this.state.data.children是未定義的。 在this.state.data中沒有名為子項的鍵。 你可以做

 {<ImagesList data={this.state.data.data.children}/>}

NB。 不要忘了按照上面的注釋中所述驗證JSON值並將其解析為Json。

 getImages: function(){
  $.ajax({
    url: this.props.url,
    dataType: 'json',
    success: function(data){
      this.setState({data: JSON.parse(data)});
    }.bind(this),
    error: function(xhr, status, err){
      console.error(url, status, err.toString());
    }.bind(this)
  });
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM