【发布时间】:2021-09-22 04:13:31
【问题描述】:
我在我的 React Native 代码中使用 Array.prototype.map() 来呈现列表中的一些类别,每个类别都可以作为 TextInput 进行编辑。我在父元素级别使用唯一键来呈现映射数组,但我仍然收到以下错误:
Warning: Encountered two children with the same key, [object Object]
有问题的代码块如下:
const CategoriesScreen = ({ navigation }) => {
// Redux
const categories = useSelector((state) => state.auth.categories);
const dispatch = useDispatch();
return (
<ScrollView style={styles.flex}>
<View style={styles.container}>
<View style={styles.textContainer}>
<Text>Category</Text>
</View>
<View style={styles.textContainer}>
<Text>Update Priority</Text>
</View>
<Spacer />
</View>
{categories.map((category, index) => {
return (
<View key={category.id} style={styles.container}>
<View style={styles.subContainer}>
<TextInput
multiline
style={styles.textBoxes}
value={category.name}
onChangeText={(text) =>
dispatch(updateCategoryName({ index, text }))
}
/>
</View>
<View style={styles.subContainer}>
<View style={styles.icon}>
<AntDesign
name="up"
size={24}
color="black"
onPress={() => dispatch(increasePriority(index))}
/>
</View>
<View style={styles.icon}>
<AntDesign
name="down"
size={24}
color="black"
onPress={() => dispatch(decreasePriority(index))}
/>
</View>
</View>
<View style={styles.subContainer}>
<Feather
name="delete"
size={40}
color="black"
onPress={() => dispatch(deleteCategory(index))}
/>
</View>
</View>
);
})}
<AntDesign
name="plussquare"
size={40}
color="black"
style={styles.addButtonStyle}
onPress={() => dispatch(addCategory())}
/>
</ScrollView>
);
};
我正在映射的数据数组的一个例子:
const categories = [
{
"id": "dc4422e4-1fff-cf90-ce9b-1fd57348cd52",
"name": "Uncategorized"
},
{
"id": "add5cb6c-53e6-30e7-b9be-b48ad394e216",
"name": "new1"
},
{
"id": "3fa3cb68-38d5-f54b-2cc0-f0584089c1c2",
"name": "new2"
},
]
您可以看到每个 id 都是完全唯一的。谁能帮我理解为什么我会收到这个关键错误?
【问题讨论】:
-
您确定类别有您认为的数据吗?调试和确认类别是包含您共享的示例数据的实际数组。
-
确实如此。我去仔细检查了。这是我最近尝试的控制台日志: Array [ Object { "id": "9301ef97-336c-e323-977d-8852e818d760", "name": "Uncategorized", }, Object { "id": "f4b48003 -8624-d971-de52-661ca87d6859", "name": "new1", }, ]
标签: reactjs react-native key array.prototype.map