列表中的每个孩子都应该有唯一的'key'道具



我一直收到这个警告"列表中的每个子项应该具有唯一的"密钥"道具";尽管我有不同钥匙的独特物品。

每当我创建一个新的"植物"对象时,我都会给它一个新uuid

setPlants(prevItems => {
return [
{name: newPlantName, key: uuid.v4(), timeInterval: null},
...prevItems,
];

我的listItem组件是用一个关键的设置的

<ListItem
key={plant.key}

每当我打印我的列表时,所有的"密钥"都有一个不同的uuid。每次刷新应用程序时都会出现警告,所以可能是因为我正在使用数据库访问数据?我真的不确定,但我使用mmkv来存储我所在州的数据,然后在应用程序第一次打开时显示这些数据。

这是完整的映射:

{plants &&
plants.map(plant =>
plant ? (
<PlantItem
plant={plant}
deletion={openDeleteOrCancel}
setPlants={setPlants}
/>
) : null,
)}

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}
/>
)}
</>
);

这就是我的状态启动的方式

const [plantsStorage, setPlantsStorage] = useStorage('plantss');
const [plants, setPlants] = useState(plantsStorage ? plantsStorage : []);
useEffect(() => {
setPlantsStorage(plants);
});

这个警告真的很烦人,如果没有办法更改我的代码来修复它,有办法以某种方式将其静音吗?只是针对这个特定的警告,而不是所有的警告。

React键应用于最外层映射元素。

反应列表和密钥

{plants.map(plant =>
plant ? (
<PlantItem
key={plant.key} // <-- use key here!
plant={plant}
deletion={openDeleteOrCancel}
setPlants={setPlants}
/>
) : null,
)}

建议,对plants数组进行过滤,去除空";孔";。

{plants
.filter(Boolean) // include only truthy plant objects
.map(plant => (
<PlantItem
key={plant.key} // <-- use key here!
plant={plant}
deletion={openDeleteOrCancel}
setPlants={setPlants}
/>)
)}

相关内容

最新更新