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

时间:2015-02-13 16:06:47

标签: javascript reactjs

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

然后将那些所述图像显示在'content'div中。通常情况下,我会用for循环来解决这个问题,但有一种特殊的方法我应该用反应来处理它吗?

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

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

1 个答案:

答案 0 :(得分:12)

以下是使用map方法中的render函数执行此操作的方法:

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/