javascript - Dynamically mapping an array of objects to table row - Stack Overflow

I'm trying to map an array of objects to table rows in React. I've tried countless suggestion

I'm trying to map an array of objects to table rows in React. I've tried countless suggestions on this site but nothing seems to render in the end.

I'm getting the array data from the db on ponentWillMount as so:

         ponentWillMount(){
         db.collection("games")
         .onSnapshot(function(querySnapshot){
             querySnapshot.forEach(function(doc){
                 games.push(doc.data())
             });
             console.log(games);
         })
      }

The data is loading properly as seen in games. games is declared as a global variable outside the react class.

So far I've tried mapping over the array like this:

renderRow = () => {
    games.map(function(val, i){
        return(
            <tr>
                <td key={i}>
                    {val.name}
                </td>
            </tr>
        )
    })
}

And then rendering it in the table like so:

            <table className="ui inverted table">
                <thead>
                    <tr>
                        <th>Lobby name</th>
                        <th>Players</th>
                        <th>Mode</th>
                        <th>Difficulty</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                   {this.renderRow()}
                </tbody>
            </table>

But nothing seems to render. I'm not sure if i'm not mapping over it properly, or perhaps it's rendering the table values before the array is loaded with data. Any thoughts on this?

Edit: console.log(games) gives this:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
currentPlayers: 1
difficulty: ""
gameMode: "family"
host: "###########"
name: "Testing new reset"
players:
player: "###########"
__proto__: Object
timestamp: 1550704627051
__proto__: Object
1: {currentPlayers: 1, difficulty: "heroic", gameMode: "experienced", host: "", name: "Testtest", …}
2: {currentPlayers: 1, difficulty: "veteren", gameMode: "experienced", host: "", name: "Flashpoint experts only!", …}

I'm trying to map an array of objects to table rows in React. I've tried countless suggestions on this site but nothing seems to render in the end.

I'm getting the array data from the db on ponentWillMount as so:

         ponentWillMount(){
         db.collection("games")
         .onSnapshot(function(querySnapshot){
             querySnapshot.forEach(function(doc){
                 games.push(doc.data())
             });
             console.log(games);
         })
      }

The data is loading properly as seen in games. games is declared as a global variable outside the react class.

So far I've tried mapping over the array like this:

renderRow = () => {
    games.map(function(val, i){
        return(
            <tr>
                <td key={i}>
                    {val.name}
                </td>
            </tr>
        )
    })
}

And then rendering it in the table like so:

            <table className="ui inverted table">
                <thead>
                    <tr>
                        <th>Lobby name</th>
                        <th>Players</th>
                        <th>Mode</th>
                        <th>Difficulty</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                   {this.renderRow()}
                </tbody>
            </table>

But nothing seems to render. I'm not sure if i'm not mapping over it properly, or perhaps it's rendering the table values before the array is loaded with data. Any thoughts on this?

Edit: console.log(games) gives this:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
currentPlayers: 1
difficulty: ""
gameMode: "family"
host: "###########"
name: "Testing new reset"
players:
player: "###########"
__proto__: Object
timestamp: 1550704627051
__proto__: Object
1: {currentPlayers: 1, difficulty: "heroic", gameMode: "experienced", host: "", name: "Testtest", …}
2: {currentPlayers: 1, difficulty: "veteren", gameMode: "experienced", host: "", name: "Flashpoint experts only!", …}
Share Improve this question edited Feb 21, 2019 at 18:52 sags95 asked Feb 21, 2019 at 18:21 sags95sags95 711 silver badge7 bronze badges 5
  • First wele to the munity, although you've joined over a year ago. Your question was worded well and so, thank you for that. Just to let you know, you can build a working snippet using Babel, React, and JSX. – Mike Commented Feb 21, 2019 at 19:01
  • @mike means not here on Stack Overflow, but on some external site. – Roko C. Buljan Commented Feb 21, 2019 at 19:06
  • @RokoC.Buljan the code snippet on StackOverflow is capable of rendering React & Babel and performing the JSX transpiling. However, it may be limited to web interfaces, so if you're using a mobile device the app interface may not allow for it. Also, if browsing from a mobile browser, you may have to put it in desktop mode depending on the device. – Mike Commented Feb 21, 2019 at 19:13
  • @Mike I know, but pasting all the code here on snippets? Would be a long one, with all the data etc... But yeah, a "working" example would be easier to play with – Roko C. Buljan Commented Feb 21, 2019 at 19:16
  • @RokoC.Buljan yes that is true, I've used it for simple things like this where it wasn't too bad, though. Still the lengthy question/example is a real possibility. A person may have to hide it on initial load and require readers to expand it. I think having the snippet yields more participation from the munity as it's easier to copy to answer than to think about about and copy/paste or type up a solution. – Mike Commented Feb 27, 2019 at 18:10
Add a ment  | 

2 Answers 2

Reset to default 5

You are not returning anything in renderRow so need to add return before games.map

Change

   renderRow = () => {
        games.map(function(val, i){
            return(
               <tr>
                  <td key={i}>
                      {val.name}
                  </td>
               </tr>
            )
        })
   }

To

  renderRow = () => {
        return games.map(function(val, i){
            return(
               <tr>
                  <td key={i}>
                      {val.name}
                  </td>
               </tr>
            )
        })
   }

If the function you are calling in ponentWillMount to fetch the games is asynchronous it may be that your React ponent renders before your data is fetched.

You should try to set the state of the ponent when the games array is fetched and the React will re-render the ponent.

eg.

class Games extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      games: []
    }
  }

  ponentWillMount() {
    db.collection("games")
      .onSnapshot(function (querySnapshot) {
        let gamesArray = []
        querySnapshot.forEach(function (doc) {
          gamesArray.push(doc.data())
        });
        this.setState({ games: gamesArray })
      })
  }

  renderRow = () => {
    return this.state.games.map(function (val, i) {
      return (
        <tr>
          <td key={i}>
            {val.name}
          </td>
        </tr>
      )
    })
  }

  render() {
    return (
      <table className="ui inverted table">
        <thead>
          <tr>
            <th>Lobby name</th>
            <th>Players</th>
            <th>Mode</th>
            <th>Difficulty</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          {this.renderRow()}
        </tbody>
      </table>
    )
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742419028a4440308.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信