You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native应用出现‘Each child in a list should have a unique key prop’警告的解决方法求助

Fixing the "Each child in a list should have a unique key prop" Warning in React Native

Hey there! Let's break down why you're seeing that warning and fix it up quickly.

Why This Warning Happens

React (and React Native) relies on unique key props to keep track of individual items in lists. This helps it efficiently update only the items that change, instead of re-rendering the entire list every time something updates. When you render a list of elements (like with map() or FlatList), every child element needs a unique, stable key so React can identify it correctly.

Where the Problem Is in Your Code

Looking at your renderItem function, you're using data.map(el => (...)) to generate a list of TouchableOpacity elements—but you aren't adding a key prop to each one! While your outer FlatList has a keyExtractor set up correctly, the inner list created by data.map also needs its own unique keys.

The Fix

Each item in your data array already has a unique key property (like id-5, id-6, etc.), so we just need to pass that as the key prop to the TouchableOpacity inside the map call.

Here's the updated renderItem function:

const renderItem = ({item: {title, data, key}}) => (
  <View>
    <Text style={styles.headingText}>{title}</Text>
    <View style={styles.item}>
      {data.map(el => (
        <TouchableOpacity 
          key={el.key} // Add this line to fix the warning!
          style={[ 
            { 
              backgroundColor: el.isCheck ? '#00ACED' : 'transparent', 
              padding: 20, 
              borderColor: '#185268', 
              borderWidth: 2, 
              borderRadius: 40, 
            }, 
          ]}>
          <Text style={styles.btnText}>{el.name}</Text>
        </TouchableOpacity>
      ))}
    </View>
  </View>
);

Quick Extra Tip

Avoid using array indexes as keys unless your list is completely static (never reorders, adds, or removes items). Indexes can cause unexpected behavior if the list changes, since React might mix up items. Since you already have unique, stable keys for each item (like id-5), using those is the ideal approach.

内容的提问来源于stack exchange,提问作者Abdul Basit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:37:37