ys memos

Blog

Reactのunique "key" prop警告の解消方法


react

2021/04/03

Reactで開発をしていたら,ブラウザのconsoleに謎の警告が出た.

普段なら無視することが多いが,今回は気が乗っていたので原因と解消方法を記す.


この警告は,npm startで建てたローカルホスト内で出力されたものである.

Warning: Each child in a list should have a unique "key" prop.

Check the render method of `Sheet`. See https://reactjs.org/link/warning-keys for more information.
    at Cell (http://localhost:3000/static/js/main.chunk.js:87:63)
    at Sheet (http://localhost:3000/static/js/main.chunk.js:145:63)
    at header
    at div
    at App (http://localhost:3000/static/js/main.chunk.js:201:63)
    at Provider (http://localhost:3000/static/js/main.chunk.js:434:3)
console.<computed> @ index.js:1

<Cell />コンポーネントを自分で定義し,以下のように表の形式を表していた.

  return(
    <div className="sheet">
      {state.data.map((row, i) => {
        return(
          <div>
            {row.map((elm, j) => {
              return <Cell i={i} j={j} />
            })}
          </div>
        )
      })}
    </div>
  );

Reactがitemsの変更,追加,削除を識別するためにkeyというpropsが必要になるとのことであった.


以下のように,各<Cell />が重複しないkeypropsを持つようにすると良い.

  return(
    <div className="sheet">
      {state.data.map((row, i) => {
        return(
          <div key={i}>                              // 変更点
            {row.map((elm, j) => {
              return <Cell key={j} i={i} j={j} />    // 変更点
            })}
          </div>
        )
      })}
    </div>
  );

Reactの公式ドキュメントに載っていた.

関連タグを探す