2016-02-04 48 views
1

我在React中構建組件。在我嘗試循環遍歷一個狀態之前,一切似乎都很完美。反應:在狀態中循環訪問數組

這是我的組分:

var BidItem = React.createClass({ 
    getInitialState: function() { 
     return { 
     theMaxBid: '', 
     theHighestBids: '' 
     }; 
    }, 
    componentDidMount: function() { 
     var $component = this; 
     $.ajax({ 
     type : "post", 
     dataType : "json", 
     url : myAjax.ajaxurl, 
     data : {action: "get_max_bid"}, 
     }) 
     .done(
     function(response){ 
      $component.setState({ 
      theMaxBid: response.max_bid, 
      theHighestBids: response.highest_bids 
      }); 
     } 
    ); 
    }, 
    render: function() { 
     var dd = [{ids:"2"}, {ids:"5"}]; 
     var cc = this.state.theHighestBids; 
     console.log(cc); 
     console.log(dd); 

     return (
     <div> 
      <p>Max Bid: {this.state.theMaxBid}</p> 
     </div> 
    ) 
    } 
    }); 

這工作,並在渲染功能CC和DD輸出陣列看起來像:

logging the custom dd array and the cc array stored in the state

當我循環通過CC數組(來自狀態)在渲染函數內:

{cc.map(function(result){ 
      console.log(result); 
      })} 

我得到以下錯誤:

Uncaught TypeError: cc.map is not a function 

但是當我通過下面的DD陣列環,它的工作原理:

{dd.map(function(result){ 
      console.log(result); 
      })} 

我爲什麼不能循環狀態數組?

回答

2

函數componentDidMount get在第一次渲染調用後運行,所以初始渲染將不會有this.state.theHighestBid(提示:highestBid)。第一次渲染運行this.state.theHighestBid返回'',它沒有#map函數。

變化getInitialState年代到theHighestBid: [],它會通過一個空陣圖的第一次,然後打電話給你的AJAX當組件支架,然後你會得到這將填充這會使第二時間的狀態響應。

0

Why can't I loop the state array?

因爲你沒有數組! theHighestBids: ''創建一個空字符串。

變化

getInitialState: function() { 
    return { 
    theMaxBid: '', 
    theHighestBids: '' 
    }; 
} 

getInitialState: function() { 
    return { 
    theMaxBid: '', 
    theHighestBids: [] 
    }; 
} 

並確保response.highest_bid也是一個數組。