1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】ulidで定義したidを渡しているはずなのに「Encountered two children with the same key `id~~」

1
Posted at

はじめに

  • reactのmapのkeyエラー

問題

  • idを文字列で渡していた
    const records = [
        { id: '01M1EC6CM3TP8Q5A7ZWNEC7RRJ', title: "ホゲホゲ", time: 1 },
        { id: '01M1EC6S0HYFPNJZ0XWFA04KEQ', title: "ふがふが", time: 3 },
        { id: '01M1EC751T2H2KDR2S09GY33E3', title: "ぴよぴよ", time: 5 }
    ];

    return (
      <>
          <ul>
              {records.map((record) => {
                  const { id, title, time } = record;
                  return (<li key="id">{title}: {time}時間</li>)
              })}
          </ul>
      </>
  )

解決

  • idを要素のプロパティから取得して解決
    const records = [
        { id: '01M1EC6CM3TP8Q5A7ZWNEC7RRJ', title: "ホゲホゲ", time: 1 },
        { id: '01M1EC6S0HYFPNJZ0XWFA04KEQ', title: "ふがふが", time: 3 },
        { id: '01M1EC751T2H2KDR2S09GY33E3', title: "ぴよぴよ", time: 5 }
    ];

    return (
      <>
          <ul>
              {records.map((record) => {
                  const { id, title, time } = record;
                  return (<li key={id}>{title}: {time}時間</li>)
              })}
          </ul>
      </>
  )

終わりに

  • コード読んですぐ分からずとりあえず検索してみて、このあたりを読んでいる時「あ、文字列で渡してた」と気付いた
  • 検索の方がAIに聞くより視野狭くなりにくいかも
1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?