LoginSignup
1
2

More than 1 year has passed since last update.

【React】 Each child in a list should have a unique "key" prop.のエラー解決

Posted at

エラー発生

AWS amplifyのSNSチュートリアルを実装中に、下記エラーに遭遇しました。

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

Check the render method of `PostList`. See https://reactjs.org/link/warning-keys for more information.
    at span
    at PostList (http://localhost:3000/static/js/main.chunk.js:667:3)
    at PostsBySpecifiedUser (http://localhost:3000/static/js/main.chunk.js:1206:69)
    at Route (http://localhost:3000/static/js/vendors~main.chunk.js:573926:29)
    at Switch (http://localhost:3000/static/js/vendors~main.chunk.js:574128:29)
    at Router (http://localhost:3000/static/js/vendors~main.chunk.js:573561:30)
    at HashRouter (http://localhost:3000/static/js/vendors~main.chunk.js:573226:35)
    at ThemeProvider (http://localhost:3000/static/js/vendors~main.chunk.js:434157:24)
    at div
    at App (http://localhost:3000/static/js/main.chunk.js:218:91)
    at Provider (http://localhost:3000/static/js/vendors~main.chunk.js:570746:20)

エラー文を翻訳すると、

警告 リストの各子は、ユニークな "key "propを持つ必要があります。

のようになるので、該当箇所を探してみました。

エラー箇所特定

詳細は省きますが、下記コードが今回のエラーの原因となります。

example.tsx
  {posts.map((post) => (
            <span>
              <PostItem post={post} />
              <Divider component="li" />
            </span>
          ))}

エラー解決

こちらの記事を参考に、mapで囲われている要素の親(?)要素である<span>keyを設定することで、無事にエラーを解消することが出来ました。

example.tsx
  {posts.map((post) => (
            <span key={post.id}>
              <PostItem post={post} />
              <Divider component="li" />
            </span>
          ))}

まとめ

最近はエラー文をよく読み、内容をきちんと理解することを心がけています。

エラー文を理解して、解決につながる箇所を仮定し、その仮定に基づいて検索をかけていきます。

そのように順序立ててエラーを紐解いていくことで、いままでよりエラー解決に至るまでの時間も短くなりましたし、解決できた理由も明確にすることが出来るようになりました。

この調子で、今後もエラーときちんと向き合って行こうと思います。

1
2
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
2