我不断收到这个警告“列表中的每个 child 都应该有唯一的‘ key ’ Prop ”,即使我有带有不同 key 的独特元素。
每当我创建一个新的“植物”对象时,我都会给它一个新的 uuid
setPlants(prevItems => {
return [
{name: newPlantName, key: uuid.v4(), timeInterval: null},
...prevItems,
];
我的 listItem 组件设置了一个键
<ListItem
key={plant.key}
每当我打印列表时,所有“键”都有不同的 uuid。每次我刷新应用程序时都会出现警告,所以可能是因为我正在使用数据库访问数据?我不太确定,但我正在使用 mmkv 存储来 self 的状态的数据,然后在应用首次打开时显示该数据。
这是完整的映射:
{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 键。
react Lists and Keys
{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}
/>)
)}
关于javascript - 列表中的每个 child 都应该有唯一的 'key' prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68383084/