reactjs - 反应原生 - 使用 Array.prototype.map() 时键无法正常工作
问题描述
我在我的 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 都是完全唯一的。谁能帮助我理解为什么我会收到这个关键错误?
解决方案
纳克酸盐
当你在render函数内的map函数中渲染 React 组件时,你必须为每个组件提供一个唯一的key prop,否则 React 会在控制台中发出警告,并且在渲染时可能会或可能不会更新你的组件。
所以解决方案将是一个关键的道具,应该是唯一的、稳定的和可重复的。
{categories.map((category, index) => {
return (
<View category={category} key={category.id} style={styles.container}>
<View style={styles.subContainer}>
<TextInput
multiline
style={styles.textBoxes}
value={category.name}
onChangeText={(text) =>
dispatch(updateCategoryName({ index, text }))
}
在这种情况下,最佳做法是使用支持您的对象的唯一 ID。
推荐阅读
- python - Django HStoreField 来自 shell 的不同输出
- facebook - 对于带有注册/登录链接的网络电子邮件身份验证 - 哪个是 FB Account Kit 的最佳替代品?Twilio 或 Firebase 之类的?
- python - 如何在 python pandas 中的数据帧上执行 groupby 时保留带有空(nan)单元格的行
- javascript - 如何使用锚标记上的 javascript 下载从 Sharepoint 列表中获取的 excel 表
- apache-spark - Spark SQL、pyspark中可以使用SQL递归吗?
- python - 从消息中获取关键字
- android - 下载管理器有时显示不成功
- tensorflow - Tensorflow Serving 错误服务 tensorflow 1.5 版模型
- matlab - 在 MATLAB 中叠加两个图
- python - 获取列表python的所有加法和减法组合