简体   繁体   中英

Trying to set the state in react via a loop and a ajax request

I am fooling around with a loop and a ajax request in react I cannot seem to get working. Its suppose to loop over, set the object array and then push that object array to the state for later use.

The issue is that I am failing at promises in general. I am using this concept from the react docs to set the state of a component upon mounting to return an array of "links".

/** @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)
  }
});

The gist of whats going on above is:

I have a bunch of comments coming in and I take the first five. From there I loop over each comment object and grab the title, creating my api link. With that I want to say get me the post based on this link, assuming it works we then want to set a temp object, this will create "five arrays" each going from a count of 1,2,3,4 and finally 5 elements.

from there we take that and set the state. This part works, but because its a ajax request the state out side the request is empty even if I use the if (isMounted()){ ... } option.

any idea how I can set the state doing something like this and still have access to it?

You either want async.js or promises to help manage multiple async actions. Async integrates a bit better with jQuery, so I'll show it with that.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM