簡體   English   中英

如何在 map 中為我的密鑰道具生成唯一密鑰? 反應

[英]How can i generate a unique key for my key prop inside a map? React

我有這個代碼:


class Board extends Component {
  static defaultProps = {
    nrows: 5,
    ncols: 5,
    chanceLightStartsOn: 0.25
  };

  constructor(props) {
    super(props);
    this.state = {
      hasWon: false,
      board: this.createBoard(),
      counter: 0,

    };

      this.createBoard = this.createBoard.bind(this);
      this.keyCount = this.keyCount.bind(this);
  }
[...]
   render() {

    const mainBoard = Array.from({length: this.props.nrows}).map(() => (
        <tr>
          {Array.from({length: this.props.ncols}).map((x, index) => (
            <Cell key={this.state.counter + 1} onClick={() => this.flipCellsAround()} isLit={this.props.chanceLightStartsOn > Math.random()} />
            ))}
        </tr>
      ));

    return (
      <table className="Board">
        <tbody>
          <h1>BOARD</h1>
          {mainBoard}
        </tbody>
      </table>

    );

我希望在每次迭代中我的key都增加一個,所以它是唯一的。 我嘗試了很多東西,但都沒有成功。 是否可以將 function 傳遞給key ,然后在每次迭代時將其遞增 1?

如果您不調整表的大小,您可以簡單地將index變量傳遞給 key prop ,並將其與外部map()中的索引結合起來 理想情況下,這將是一個與列的內容有某種邏輯聯系的數字,因此如果Cell組件發生更改,react 會知道重新呈現您的列。

const mainBoard = Array.from({length: this.props.nrows}).map((ignored, rowIndex) => (
    <tr>
      {Array.from({length: this.props.ncols}).map((x, idx) => (
        <Cell key={rowIndex * this.props.nrows + idx} onClick={() => this.flipCellsAround()} isLit={this.props.chanceLightStartsOn > Math.random()} />
        ))}
    </tr>
  ));

這是一個片段來說明這一點:

var rows = Array.from({ length: 10 });
var cols = Array.from({ length: 5 });
var mainBoard = rows.map((ignored, rowIndex, rows) => {
  return cols.map((ignoredCol, colIndex, col) => {
    return rows.length * rowIndex + colIndex;
  })
});

console.log(mainBoard)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM