2016-02-04 82 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也是一个数组。