首页 > 解决方案 > Ionic + React.js:警告:列表中的每个孩子都应该有一个唯一的“关键”道具

问题描述

我将 firebase 用于数据库,将 Ionic + React 用于移动应用程序。我已经将我的 firebase 数据转换为数组,但是当我想映射这些值时。它告诉我它应该有一个唯一键,但我已经在元素的返回函数中放置了一个唯一键。有人能告诉我我做错了什么吗?谢谢。

这是我将对象转换为数组的代码

const Tab2: React.FC = () => {
  const [doctors, setDoctor] = React.useState([]);

  useIonViewWillEnter(()=>{
    console.log('Enter')
    firebase.database().ref('users').orderByChild('type').equalTo('doctor').on('value',(snapshot)=>{
          setDoctor(Object.keys(snapshot.val()).map(key => ({ [key]: snapshot.val()[key] })))
        })
    console.log(doctors)

  })

而在我的回报

        <IonList>
        {doctors.map(elem => {
            return(
              <IonItem key={elem['uid']}>
              <IonLabel>
                <IonText className="font-weight: bold;">
                <h3>{elem['name']}</h3>
                </IonText>
                <h4>{elem['speciality']}</h4>
                <h4>{elem['email']}</h4>
              </IonLabel>
              <br></br>
            </IonItem> 
            )
          })}
        </IonList>

我得到的是Warning: Each child in a list should have a unique "key" prop.

我的火力基地结构

在此处输入图像描述

更新:console.log(doctors)只会输出一个像这样的空数组[],我不知道为什么。在组件进入之前,我已经把它放在了一个方法中。

标签: javascriptreactjsloopsionic-frameworkfirebase-realtime-database

解决方案


注意:这只是一个警告,而不是错误。

这是正确的做法。

<IonList>
  {doctors.map((elem, index) => {
    // index has to come from the second parameter from map
    
    return (
      <IonItem key={index}>
        <IonLabel>
          <IonText className="font-weight: bold;">
            <h3>{elem["name"]}</h3>
          </IonText>
          <h4>{elem["speciality"]}</h4>
          <h4>{elem["email"]}</h4>
        </IonLabel>
        <br></br>
      </IonItem>
    );
  })}
</IonList>;

索引必须放在第一个/父 div 元素中。在这种情况下,它将是<IonItem>

参考:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

另外,根据您没有获取数据。像这样调整你的代码。您只需要创建一个新的 arr,然后通过快照来获取密钥。

将具有相应键的对象推送到新的 arr,因此它可以在没有特定键名的情况下进行迭代,例如eA9w5ynhqN9iT7kKDBt2Ane9VF3

useIonViewWillEnter(() => {
  console.log("Enter");
  let newArr = [];
  firebase
    .database()
    .ref("users")
    .orderByChild("type")
    .equalTo("doctor")
    .on("value", (snapshot) => {
      let key;
      snapshot.forEach((childSnap) => {
        key = childSnap.key; // im just getting the key
        const snapVal = snapshot.val(); // getting the object
        newArr.push(snapVal[key]); 
      });
      setDoctor(newArr);

      // console.log(doctors)
    });
});

推荐阅读