简体   繁体   English

使用React JS的组件“循环”

[英]Component “loop” with React JS

I'am studying React JS library, and i wish create a "loop" of component, returning array values from json file. 我正在研究React JS库,我希望创建一个组件的“循环”,从json文件返回数组值。 Here my json file: 这是我的json文件:

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

My react component: 我的反应成分:

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')
  );

When I run the code, returning this error: 当我运行代码时,返回此错误:

Uncaught TypeError: Cannot read property 'map' of undefined. Uncaught TypeError:无法读取未定义的属性“ map”。

I dont know how to fix that. 我不知道该如何解决。

JSON input data seems to be invalid. JSON输入数据似乎无效。 Validated it on JSONParser JSONParser上进行了验证

ImageList component expects children JSON Array inside the data object. ImageList组件期望data对象内有children JSON Array。 So if AJAX call returns following JSON, component would be able to render that data 因此,如果AJAX调用返回以下JSON,则组件将能够呈现该数据

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

Please note that this.setState({data: data}); 请注意, this.setState({data: data}); is already having data variable. 已经具有data变量。 So the response should not again set data else it becomes data.data.children . 因此,响应不应再次设置data否则它将变为data.data.children That is why code is throwing Uncaught TypeError: Cannot read property 'map' of undefined. 这就是代码抛出Uncaught TypeError: Cannot read property 'map' of undefined.

For further reading after you complete ReactJS study, I would recommend to check Flux Architecture , which is recommended way of implementing ReactJS applications 为了在您完成ReactJS学习之后进一步阅读,我建议检查Flux Architecture ,这是实现ReactJS应用程序的推荐方法

Lets debug your code. 让我们调试您的代码。 in the ajax callback function at your code. 在代码的ajax回调函数中。 you gets the json data returns and you set the state data with the return data. 您将获得json数据返回,并使用返回数据设置状态数据。 So this.state.data will be: 因此this.state.data将是:

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

And in the render method you are trying to insert props to ImagesList from ImageBox as 并且在render方法中,您尝试将props从ImageBox插入到ImagesList中,如下所示:

data = { this.state.data.children }

but this.state.data.children is undefined. 但是this.state.data.children是未定义的。 there is no key named children in this.state.data. 在this.state.data中没有名为子项的键。 You can do 你可以做

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

NB. NB。 Dont forget to validate the JSON value as described in above comment and Parse it to Json. 不要忘了按照上面的注释中所述验证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