反应.js通过数组创建循环

React.js create loop through Array

本文关键字:创建 循环 数组 js 反应      更新时间:2023-09-26

>我正在尝试显示 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.

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

我错过了什么?

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

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

此外,由于.map中的player Object您应该从中获取属性

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

Example

正如@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>
        );
    }

您可以在执行类似映射之前简单地进行条件检查

{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>
 ))
}

上述两个功能都做同样的事情