React.js create loop through Array

后端 未结 3 1301
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 02:36

I\'m trying to display a Table of 10 Players. I get the data from via ajax and pass it as props to my Child.

var CurrentGame = React.createClass({

  // get          


        
相关标签:
3条回答
  • 2020-12-08 02:52

    As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

    The alternative to the solution they provided would be to prevent render until participants exist, something like this:

        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>
            );
        }
    
    0 讨论(0)
  • 2020-12-08 03:09

    You can simply do conditional check before doing map like

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

    Now a days .map can be done in two different ways but still the conditional check is required like

    .map with return

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

    .map without return

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

    both the above functionalities does the same

    0 讨论(0)
  • 2020-12-08 03:18

    In CurrentGame component you need to change initial state because you are trying use loop for participants but this property is undefined that's why you get error.,

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

    also, as player in .map is Object you should get properties from it

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

    Example

    0 讨论(0)
提交回复
热议问题