【问题标题】:Warning: Each child in a list should have a unique "key" prop. React Native警告:列表中的每个孩子都应该有一个唯一的“关键”道具。反应原生
【发布时间】:2021-07-18 15:14:58
【问题描述】:

您好,我正在尝试使用 react native 构建一个迷你社交媒体应用,收到以下错误:

警告:列表中的每个孩子都应该有一个唯一的“key”属性。

查看VirtualizedList的渲染方法

也尝试使用 results.map 而不是平面列表。 并且还使用stackoverflow上的解决方案更改密钥提取器,但没有成功。 有人可以帮忙吗?

代码:

    return (
    <FlatList
      style={{flex:1}}
      data={results}
      keyExtractor={(item, index) => {
        return item.id;
      }} 
      renderItem={({item}) => <TouristCard key={item.id} item={item} onPress={()=> navigation.navigate('HomeProfile', {userId: item.userId})} /> }
    />
);

旅游卡:

const TouristCard = ({item,onPress}) => {

return (   
    <View key={item.id} style={styles.listItem} >
      <UserImg  source={{uri: item.userImg ? item.userImg : 'https://lh5.googleusercontent.com/-b0PKyNuQv5s/AAAAAAAAAAI/AAAAAAAAAAA/AMZuuclxAM4M1SCBGAO7Rp-QP6zgBEUkOQ/s96-c/photo.jpg'}}/>
      <View style={{alignItems:"center",flex:1}}>
        <Text style={{fontWeight:"bold"}}>{item.fname ? item.fname : 'Annonymous' } {item.lname ? item.lname : '' }</Text>
        <Text>{item.flightDesc}</Text>
        <Text style={{fontWeight:"bold"}}>{item.age}</Text>
      </View>
      <Text style={{color:"blue"}}>View Profile</Text>
    </View>
);

结果对象:

   const filterByDates = (results,startDate,endDate) => {
    return results.filter(res => {
        return startDate<res.endDate && res.startDate<endDate;
    });
};

useEffect(() => {
    const fetchCommunity = async() => {
        try {
            //const list = [];
            await firestore()
            .collection('flights')
            .where("destination","==",destination)
            .where("user","!=",user.uid)
            .get()
            .then((querySnapShot) => {
                querySnapShot.forEach(doc => {
                    const {user,flightDesc,startDate,endDate} = doc.data();
                    list.push({
                        user: user,
                        flightDesc,
                        startDate,
                        endDate
                    });
                })
                
            })  
            setResults(filterByDates(list,startDate,endDate));
            fetchProfiles();
        } catch(e) {
            console.log(e);
        }
    }
    const fetchProfiles = async() => {
        try {
            //const list2=[];
            list.forEach(async obj => {
                await firestore()
                .collection('users')
                .where("userId","==",obj.user)
                .get()
                .then((querySnapShot) => {
                querySnapShot.forEach(doc => {
                    const {userImg,age,fname,lname} = doc.data();
                    list.push({
                        id: doc.id,
                        userImg,
                        age,
                        fname,
                        lname
                    });
                })
                
            })  
            setResults(list);
            console.log(list);
            })
        } catch (e) {
            console.log(e);
        }
    }
    fetchCommunity();
},[]);

【问题讨论】:

  • 您是否已验证密钥提取器实际上为每个元素返回了一个唯一的 ID,如您所期望的那样?

标签: react-native key flatlist


【解决方案1】:

用这个替换你的Flatlist

<FlatList
   style={{flex:1}}
   data={results}
   keyExtractor={(item) => item.id.toString()} // Here was the error
   renderItem={({item}) => <TouristCard item={item} onPress={()=> navigation.navigate('HomeProfile', {userId: item.userId})} /> }
/>

还要检查results 的每个元素是否有唯一的id

还有MAIN 点...检查您的数组项是否有一个名为id 的属性。如果userId 是唯一的,则如上所示使用它

【讨论】:

  • 现在我得到这个错误:[TypeError: undefined is not an object (evalating 'item.userId.toString')]
  • 再次编辑答案检查
  • 如果您仍有问题,请在问题中发布您的results。它是什么样的?
  • 我贴了,还是一样,请帮忙,检查一下,结果不为空,密钥是唯一的,但是密钥提取器看起来像空,它不读取 toString() ,说它未定义。
  • 我不是要这个...只是console.log(results) 并显示输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
  • 2020-12-30
  • 2019-12-07
  • 1970-01-01
  • 2019-08-04
  • 2021-01-12
  • 2022-06-28
相关资源
最近更新 更多