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 Native】map関数使用時のキー重複エラー

Last updated at Posted at 2025-04-01

エラー内容

卒業制作の実装で下記エラーが発生しました。

Warning: Encountered two children with the same key, `5`. 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.

エラーが起きた箇所

mapSample.tsx

<View style={styles.radioItemGrid}>
    {options.map((option) => (
        <RadioButton.Item 
            key={option.optionId} // ここでエラー
            label={option.optionName}
            value={String(option.optionId)}
        />
    ))}
</View>

原因

keyの値にindexが必要だった。
現状の実装だとkey指定のoptionIdが重複してしまう場合があるため、
map関数の引数にindexを追加してキーをUniqueにすることで解消されました。

修正後のソース

mapSample.tsx
<View style={styles.radioItemGrid}>
    {options.map((option, index) => (
        <RadioButton.Item 
            // ここにindexを追加して、キーをUniqueにする
            key={`${option.optionId}-${index}`} 
            label={option.optionName}
            value={String(option.optionId)}
        />
    ))}
</View>

参考にした記事は下記です

indexを追加する場合の注意点

indexをキーとして使用するのは、以下の条件を満たす場合に限ります。
【画面表示後】

  • リストの順序が変わらない(ソートなどで順序が変更されない)
  • リストの内容が動的に変更されない(リストの追加・削除が行えない)

対応後に気づいたこと

indexで対応してエラーは無くなったのですが、
改めて見直すと、別画面でキー自体が重複して登録されてしまうのが問題だとわかり、
今回の修正後のソース対応はせずに修正前のソースに戻しました。

どちらかというと、改めてmap関数についての気づきと
エラー調査の履歴を残す目的でこちらの記事を書かせていただきました。
気付いたこと、改めて勉強になったな!と思ったことは
どんどんOUTPUTして行こうと思います。

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?