简单的Ajax请求,在React.js中循环数据

Simple Ajax request, that loops over data in React.js

本文关键字:js 循环 数据 React Ajax 请求 简单      更新时间:2023-10-30

新的反应,而不是100%关于我应该如何处理这个相对简单的问题。我目前正在从Reddit上收集一些图片,将这些图片推回到"图片"状态。

然后让这些图像显示在"内容"分区中。通常,我只会用for循环来处理它,但有没有一种特殊的方法可以用react来处理它?

componentDidMount: function() {
      var self = this;
      $.get(this.props.source, function(result) {
        var collection = result.data.children;
        if (this.isMounted()) {
          this.setState({
            //Should I put a for loop in here? Or something else?
            pImage: collection.data.thumbnail
          });
        }
      }.bind(this));
    }

Fiddle显示我的当前状态:https://jsfiddle.net/69z2wepo/2327/

以下是如何在render方法中使用map函数:

var ImageCollect = React.createClass({
        getInitialState: function() {
          return {
            pImage: []
          };
        },
        componentDidMount: function() {
          var self = this;
          $.get(this.props.source, function(result) {
            var collection = result.data.children;
            if (this.isMounted()) {
              this.setState({
                pImage: collection
              });
            }
          }.bind(this));
        },
        render: function() {
          images = this.state.pImage || [];
          return (
            <div>
              Images: 
              {images.map(function(image){
                  return <img src={image.data.thumbnail}/>
              })}
            </div>
          );
        }
      });
    React.render(
    <ImageCollect source="https://www.reddit.com/r/pics/top/.json" />,
      document.getElementById('content')
    );

这是工作小提琴:http://jsfiddle.net/2ftzw6xd/