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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28503739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:05:12  来源:igfitidea点击:

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

javascriptreactjs

提问by Starboy

New to react and not 100% on how I should approach this relatively simple problem. I'm currently looking to gather some images from Reddit, that push those images back to the 'pImage' state.

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

Then have those said images display within the 'content' div. Usually, I would just go about this with a for loop, but is there a special way I should be processing it with react?

然后将这些图像显示在“内容”div 中。通常,我会用 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 to show my current state: https://jsfiddle.net/69z2wepo/2327/

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

回答by nilgun

Here is how you would do it with a mapfunction in the rendermethod:

以下是使用方法中的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')
    );

Here is working fiddle: http://jsfiddle.net/2ftzw6xd/

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