![](/img/trans.png)
[英]i am getting error Each child in a list should have a unique "key" prop
[英]Each child in a list should have a unique "key" prop, I am getting this error in my react native app
当我尝试从 firebase firestore 获取数组数据时,出现以下错误。 我该如何解决这个问题,有人可以建议我的代码结构。
VM22 bundle.js:3927 警告:列表中的每个孩子都应该有一个唯一的“key”道具。
检查CellRenderer
的渲染方法。 有关详细信息,请参阅https://reactjs.org/link/warning-keys 。 在 http://localhost:19006/static/js/bundle.js:157320:19 在 CellRenderer (http://localhost:19006/static/js/bundle.js:172017:36)
import React, { useState, useEffect } from 'react';
import {View, Button, Text, FlatList, StyleSheet, Pressable, TouchableOpacity} from 'react-native'
import {firebase} from '../config';
const Testing = ({ navigation }) =>{
const [users, setUsers] = useState([]);
const todoRef = firebase.firestore().collection('testing');
useEffect(() => {
todoRef.onSnapshot(
querySnapshot => {
const users = []
querySnapshot.forEach((doc) => {
const { ArrayTesting
} = doc.data()
users.push({
id: doc.id,
ArrayTesting
})
})
setUsers(users)
}
)
}, [])
return (
<View style={{ flex:1,}}>
<FlatList
data={users}
numColumns={1}
renderItem={({item}) => (
<Pressable >
<View>
<View>
{ (item.ArrayTesting)
? item.ArrayTesting.map((item) => <Text>{item}</Text>)
: <Text></Text>
}
</View>
</View>
</Pressable>
)} />
</View>
);}
export default Testing;
当您在 react 中映射组件时,您必须为组件提供唯一键,以便它知道要重新渲染哪个组件。
<View>
{ (item.ArrayTesting)
// if item has unique field, please provide that as key in Text
? item.ArrayTesting.map((item,index) => <Text key={index}>{item}</Text>)
: <Text></Text>
}
</View>
嘿 flatlist 已经有一个名为keyExtractor
的属性,请使用它,以便所有元素都已经有一个唯一的键,并且您不必将任何显式传递给子组合:
<Flatlist
keyExtractor={(item, _index) => String(_index)}
/>
并且还在您的 renderItem 添加以下内容:
{ (item.ArrayTesting)
? item.ArrayTesting.map((item,index) => <Text key={index}>{item}</Text>)
: <Text></Text>
}
希望对你有帮助,有疑问欢迎交流
上面的答案是正确的,但是,我想澄清一点,上面的答案甚至有点触及。 我想再强调一点:)。
当为每个元素添加一个 key 属性时(以便 react 知道如何在 DOM 中跟踪它们),我们应该为每个<Text />
组件提供一个正确的唯一键。
这可能就像一个id: 1
属性在每个 object 或来自服务器的数据点上返回。 这将确保 React 对数据的误解令人头疼,因为您的key
只是有序索引。 如果您的数据发生更改(您更新列表以删除一项),React 可能会删除错误的项目来移动索引。
<View>
{(item.ArrayTesting)
// if item has unique field, please provide that as key in Text
? item.ArrayTesting.map((item) => <Text key={item.id}>{item}</Text>)
: <Text></Text>
}
</View>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.