フロントエンジニア芸人もりたけんじのreact

【React】これ。Warning: flattenChildren(…): Encountered two children with the same key, `keyName`. Child keys must be unique; when two children share a key, only the first child will be used.

【React】これ。Warning: flattenChildren(...): Encountered two children with the same key, `keyName`. Child keys must be unique; when two children share a key, only the first child will be used.

よく出るこれ。keyがダブった際に出るWarning

keyって何って方は
https://facebook.github.io/react/docs/lists-and-keys.html

Keys
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:

Reactにそのitemが変更されたか追加されたか削除されたか認識させるために配列要素に与える一意の識別子。と解釈しました。
これによってReactは不要なレンダリングを避け、効率よくするわけなのですね。

なので一意の識別子なのでもしプロパティにidがあるならそれをそのままidをkeyに渡せば必ずitemは一意になるわけですね。
だから下のようにする。

ただこのWarningが出るってことはkeyを設定している方です。

【React】これ。Warning: flattenChildren(...): Encountered two children with the same key, `keyName`. Child keys must be unique; when two children share a key, only the first child will be used.
【React】これ。Warning: flattenChildren(...): Encountered two children with the same key, `keyName`. Child keys must be unique; when two children share a key, only the first child will be used.

設定されているitemのkeyがダブって存在していて表示しようとしています。
reactはそこにあるようにkeyがダブった場合最初のitemのみを返すようです。

なので、APIの返り値を使ってlistを作っている場合、
APIから同じkeyに設定したid(上記の例のような場合)を持つitemがダブって返ってきている可能性があります。

そこをチェックしてみるのですね。
今日気づいたバグがその原因ぽいのでご紹介しました。。