1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript】"同じkeyがありますよ"エラーの解消

Posted at

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メソッドに関する初歩的なエラーだと思うのですが、やはり基礎的な勉強が足りていない気がします。

現在取り組んでいる開発を進めつつも、今一度しっかり基礎から学ぶ必要性がありそうです。

参考記事

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?