keyが重複していますよ問題
とある開発をする中で、ずっと出現していたエラー。
Warning: Encountered two children with the same key, `d437cb80-1b43-4e2b-8009-6e08eddee864`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
超初歩的なものですが、解決法が見つかったのでシェアいたします。
mapメソッドの引数にindexを渡す
該当箇所に、下記のようにpost.id
を渡していたのですが、これだと新しいデータを作成したときに、そのid
が重複してしまっていたみたいです。
sample.tsx
{posts.map((post: any) => (
<span key={post.id}>
<PostItem post={post} />
<Divider component="li" />
</span>
))}
これを、下記のようにindex
を渡したところ、
sample.tsx
{posts.map((post: any, index) => (
<span key={index}>
<PostItem post={post} />
<Divider component="li" />
</span>
))}
無事にエラーは消えました。
まとめ
mapメソッドに関する初歩的なエラーだと思うのですが、やはり基礎的な勉強が足りていない気がします。
現在取り組んでいる開発を進めつつも、今一度しっかり基礎から学ぶ必要性がありそうです。
参考記事