簡體   English   中英

列表中的每個孩子都應該有一個唯一的“關鍵”道具,我在我的反應原生應用程序中遇到了這個錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM