React.js通过Array创建循环

Min*_*ohn 33 javascript arrays ajax reactjs

我正在尝试显示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>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

现在我需要一个List Component来渲染玩家:

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>
    )
  }
});
Run Code Online (Sandbox Code Playgroud)

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

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

我错过了什么?

Ale*_* T. 39

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

getInitialState: function(){
    return {
       data: {
          participants: [] 
       }
    };
},
Run Code Online (Sandbox Code Playgroud)

此外,如player在.map是Object你应该从它那里得到的属性

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

Example


Dan*_*n W 16

作为@Alexander解决的问题是异步数据加载的一个-你立即渲染,你会不会有加载,直到异步Ajax调用做出决议参与者和填充data用participants.

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

    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>
        );
    }
Run Code Online (Sandbox Code Playgroud)