简体   繁体   中英

nested for loop in react render

The site is telling me there are many similar questions, but i just couldn't find an answer i'm looking for. I believe it should be an easy one for react pros, as i'm a beginner.

I've got this code inside render function:

return (
  
  <div>
    <div className="board-row">
      {this.renderSquare(0)}
      {this.renderSquare(1)}
      {this.renderSquare(2)}
    </div>
    <div className="board-row">
      {this.renderSquare(3)}
      {this.renderSquare(4)}
      {this.renderSquare(5)}
    </div>
    <div className="board-row">
      {this.renderSquare(6)}
      {this.renderSquare(7)}
      {this.renderSquare(8)}
    </div>
  </div>
);  

And i want to rewrite it using two nested loops, all I could come up with is this (doesn't work, i try to correct errors, but that just brings me to fresh errors):

return (
  <div>
   {for (let j = 0; j < 3; j++) {
      <div className="board-row">
       {for (let k = 0; k < 3; k++) {
         {this.renderSquare((j*3) + k)}
       }}
      </div>
   }}
  </div>

);

How do i rewrite this code?

There are lot of workaround for making it work, like this

My suggestion would be have a good data structure for it.

const board = [
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

return (
  <div>
   {board.map(row => (
      <div className="board-row">
       {row.map(square => renderSquare(square))}
      </div> 
   ))}
  </div>
)

and you cannot use for loop inside the render method. You should use .map for it.

Try below code:

const array = [
    {
        className: "board-row",
        squares: [2, 4, 6]
    },
    {
        className: "board-row",
        squares: [1, 2, 3]
    }
]

return (
    <div>
        {array.map((item, index) => {
            return (
                <div key={index} className={item.className}>
                    {item.squares.map((square, indexSquare) => {
                        return square;
                    })}
                </div>
            )
        })}
    </div>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM