2014-12-19 40 views
0

我在一個循環和ajax請求在反應愚弄我似乎無法工作。它假設循環,設置對象數組,然後將該對象數組推到狀態以備後用。試圖通過一個循環和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()){ ... }選項。

任何想法如何設置狀態做這樣的事情,仍然可以訪問它?

回答

0

您要麼async.js要麼承諾幫助管理多個異步操作。異步集成與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)); 
}