[英]each child in a list should have unique 'key' prop
I keep getting this warning "each child in a list should have unique 'key' prop" even though I have unique items with different keys.我不断收到此警告“列表中的每个孩子都应该有唯一的'键'道具”,即使我有具有不同键的唯一项目。
Whenever I create a new 'plant' object I give it a new uuid每当我创建一个新的“工厂”object 时,我都会给它一个新的 uuid
setPlants(prevItems => {
return [
{name: newPlantName, key: uuid.v4(), timeInterval: null},
...prevItems,
];
And my listItem component is set up with a key我的 listItem 组件设置了一个键
<ListItem
key={plant.key}
Whenever I print my list all the 'keys' have a different uuid.每当我打印我的列表时,所有“键”都有不同的 uuid。 The warning occurs every time I refresh the app so it might be somehow because i'm using a database to access the data?
每次我刷新应用程序时都会出现警告,所以它可能是因为我正在使用数据库来访问数据? I'm not really sure but I am using mmkv to store the data from my state and then I show that data when the app first opens.
我不太确定,但我正在使用 mmkv 存储 state 中的数据,然后在应用程序首次打开时显示该数据。
This is the full mapping:这是完整的映射:
{plants &&
plants.map(plant =>
plant ? (
<PlantItem
plant={plant}
deletion={openDeleteOrCancel}
setPlants={setPlants}
/>
) : null,
)}
PlantItem component: PlantItem 组件:
return (
<>
<ActionSheet
visible={actionSheetVisible}
closeOverlay={() => {
setActionSheetVisible(false);
}}
actions={actions}
/>
<ListItem
key={plant.key}
onPress={() => {
setActionSheetVisible(true);
}}
bottomDivider>
<ListItem.Content key={plant.key} style={styles.listItemContainer}>
<ListItem.Title>{plant.name}</ListItem.Title>
{/* <Icon name="check" size={20} /> */}
</ListItem.Content>
</ListItem>
{showAddTimeInterval && (
<AddTimeInterval
createTimeInterval={createTimeInterval}
closeModal={toggleShowAddTimeInterval}
plantName={plant.name}
/>
)}
</>
);
This is how my states are initiated这就是我的状态开始的方式
const [plantsStorage, setPlantsStorage] = useStorage('plantss');
const [plants, setPlants] = useState(plantsStorage ? plantsStorage : []);
useEffect(() => {
setPlantsStorage(plants);
});
The warning is just really annoying, if there is no way to change my code to fix it is there a way to mute it somehow?这个警告真的很烦人,如果没有办法改变我的代码来修复它有没有办法以某种方式静音它? just for this specific warning not all warnings.
仅针对此特定警告,并非所有警告。
The React key should be used on the outermost mapped element. React 键应该用在最外层的映射元素上。
React Lists and Keys React列表和键
{plants.map(plant => plant? ( <PlantItem key={plant.key} // <-- use key here: plant={plant} deletion={openDeleteOrCancel} setPlants={setPlants} /> ), null )}
Suggestion, filter the plants
array to remove the null "holes".建议,过滤
plants
阵列以去除 null “孔”。
{plants.filter(Boolean) // include only truthy plant objects.map(plant => ( <PlantItem key={plant.key} // <-- use key here plant={plant} deletion={openDeleteOrCancel} setPlants={setPlants} />) )}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.