尝试通过循环和ajax请求设置状态

时间:2014-12-19 02:14:27

标签: javascript ajax reactjs

我正在愚弄循环和ajax请求反应我似乎无法正常工作。它假设循环,设置对象数组,然后将该对象数组推送到该状态供以后使用。

问题是我一般都没有兑现承诺。我正在使用this concept from the react docs在安装时设置组件的状态以返回"链接的数组"。

/** @jsx React.DOM */

var Temp = {
  object: new Array()
}

var CommentsRow = React.createClass({

  getInitialState: function(){
    return {
      href: ''
    }
  },

  componentDidMount: function(){
    var self = this
    this.props.comments.slice(0, 5).map(function(comment){
      var postUrl = window.Development.API_URL + 'posts/' + comment.post_id

      $.get(postUrl, function(post){
        Temp.object.push(post.post.title);
        if (self.isMounted()) {
          self.setState({
            href: Temp.object
          });
        }
      });
    });

  },

  render: function() {
    console.log(this.state)
  }
});

上面的重点是:

我有一堆评论,我采取前五个。从那里我循环每个评论对象并抓住标题,创建我的api链接。有了这个,我想说基于这个链接给我发帖,假设它有效我们然后想要设置一个临时对象,这将创建"五个数组"每个都来自1,2,3,4和最后5个元素。

从那里我们接受并设置状态。这部分有效,但因为它的ajax请求状态在外,即使我使用if (isMounted()){ ... }选项,请求也是空的。

任何想法如何设置状态做这样的事情仍然可以访问它?

1 个答案:

答案 0 :(得分:0)

您要么async.js,要么承诺帮助管理多个异步操作。 Async与jQuery集成得更好,所以我会用它来展示它。

componentDidMount: function(){
  async.map(this.props.comments.slice(0, 5), function(comment, cb){
    var postUrl = window.Development.API_URL + 'posts/' + comment.post_id;
    $.get(postUrl, function(data){
      cb(null, {title: data.post.title, href: ???});
    });
  }, function(err, posts){
    // posts is an array of the {title,href} objects we made above
    this.setState({posts: posts});
  }.bind(this));
}