【问题标题】:React.js create loop through ArrayReact.js 通过 Array 创建循环
【发布时间】:2015-04-03 22:04:02
【问题描述】:

我正在尝试显示一个包含 10 名玩家的表格。我通过 ajax 获取数据并将其作为道具传递给我的孩子。

var CurrentGame = React.createClass({

  // get game info
  loadGameData: function() {
    $.ajax({
      url: '/example.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  },

  getInitialState: function(){
    return {data: []};
  },

  componentDidMount: function() {
    this.loadGameData();
  },

  render: function() {
    return (
      <div className="CurrentGame">
        <h1> Current Game Information</h1>
        <PlayerList data={this.state.data}/>
      </div>
    );
  }
});

现在我需要一个列表组件来渲染玩家:

var PlayerList = React.createClass({


  render: function() {

    // This prints the correct data
    console.log(this.props.data);

    return (
      <ul className="PlayerList">
        // I'm the Player List {this.props.data}
        // <Player author="The Mini John" />

        {
          this.props.data.participants.map(function(player) {
            return <li key={player}>{player}</li>
          })
        }
      </ul>
    )
  }
});

这给了我一个Uncaught TypeError: Cannot read property 'map' of undefined

我有点不确定发生了什么,我的控制台日志显示了正确的数据,但不知何故我无法在返回时访问它。

我错过了什么?

【问题讨论】:

    标签: javascript arrays ajax reactjs


    【解决方案1】:

    CurrentGame 组件中,您需要更改初始状态,因为您正在尝试对participants 使用循环,但此属性是undefined,这就是您收到错误的原因。,

    getInitialState: function(){
        return {
           data: {
              participants: [] 
           }
        };
    },
    

    另外,由于.map 中的playerObject,您应该从中获取属性

    this.props.data.participants.map(function(player) {
       return <li key={player.championId}>{player.summonerName}</li>
       // -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
    })
    

    Example

    【讨论】:

    • 能否为每个列表项添加 onClick 事件并将列表项传递给函数?打印函数中的数据?
    【解决方案2】:

    正如@Alexander 所解决的那样,问题是异步数据加载之一 - 您正在立即渲染,并且在异步 ajax 调用解决并使用 participants 填充 data 之前,您不会加载参与者。

    他们提供的解决方案的替代方案是在参与者存在之前阻止渲染,如下所示:

        render: function() {
            if (!this.props.data.participants) {
                return null;
            }
            return (
                <ul className="PlayerList">
                // I'm the Player List {this.props.data}
                // <Player author="The Mini John" />
                {
                    this.props.data.participants.map(function(player) {
                        return <li key={player}>{player}</li>
                    })
                }
                </ul>
            );
        }
    

    【讨论】:

      【解决方案3】:

      你可以在做地图之前简单地做条件检查

      {Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
         return <li key={player.championId}>{player.summonerName}</li>
         })
      }
      

      现在 .map 可以通过两种不同的方式完成,但仍然需要条件检查,例如

      .map 带返回

      {Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
         return <li key={player.championId}>{player.summonerName}</li>
       })
      }
      

      .map 没有返回

      {Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
         return <li key={player.championId}>{player.summonerName}</li>
       ))
      }
      

      以上两个功能都是一样的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-27
        • 2017-12-07
        • 1970-01-01
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多