javascript - 列表中的每个 child 都应该有唯一的 'key' prop

标签 javascript android reactjs react-native

我不断收到这个警告“列表中的每个 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/

相关文章:

javascript - jekyll 如何将他们默认的网站漂亮模板放到我的博客中?

javascript - Dstore过滤器: is there a way to compare properties?

javascript - 来自 Assets 的 Android WebView JavaScript

android - 找到重复的com.google.android.gms.location.places.zza类

javascript - window.innerHeight 与 React 和 redux

javascript - 如何将经过身份验证的用户重定向回其原始页面?

Android:垂直 Recyclerview 内的水平 Recyclerview

java - 由于某种原因,我的 java 类不会继承 public void。有人可以帮助我吗?

reactjs - 尝试使用 ConnectedRouter 进行与推送一起使用的重定向,我的 redux mapStateToProps 给出错误

reactjs - React Router V4 使用 Material UI 在 ListItem 内实现 NavLink