【问题标题】:React: Looping through an array within a stateReact:在状态中循环遍历数组
【发布时间】:2016-05-14 18:27:12
【问题描述】:

我正在 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 都输出一个如下所示的数组:

当我在渲染函数中循环遍历 cc 数组(来自状态)时:

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

我收到以下错误:

Uncaught TypeError: cc.map is not a function

但是当我遍历下面的 dd 数组时,它可以工作:

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

为什么我不能循环状态数组?

【问题讨论】:

    标签: javascript php jquery dictionary reactjs


    【解决方案1】:

    为什么我不能循环状态数组?

    因为你没有数组! theHighestBids: '' 创建一个空字符串。

    改变

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

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

    并确保response.highest_bid 也是一个数组。

    【讨论】:

      【解决方案2】:

      函数componentDidMount get 在第一次渲染调用之后运行,所以初始渲染不会有this.state.theHighestBid(提示:highestBid)。第一次渲染运行 this.state.theHighestBid 返回 '' 没有 #map 函数。

      getInitialState 更改为theHighestBid: [],它将第一次映射到一个空数组,然后在组件挂载时调用您的 AJAX,然后您将获得一个响应,该响应将填充将呈现的状态第二次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-22
        • 2019-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多