React Native应用出现‘Each child in a list should have a unique key prop’警告的解决方法求助
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

