javascript - 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)
只会输出一个像这样的空数组[]
,我不知道为什么。在组件进入之前,我已经把它放在了一个方法中。
解决方案
注意:这只是一个警告,而不是错误。
这是正确的做法。
<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)
});
});
推荐阅读
- angular - Bootstrap 4 导航栏活动背景组颜色
- apache-zookeeper - 分布式状态机的 zookeeper 集成在处理并行区域时出现错误 KeeperErrorCode = BadVersion
- vim - 如何在vim中查找和替换#(磅)字符的字符串?
- java - Spring JPA 查询返回列表
, 当存储库返回类型为 List - java - Struts 数据库列表未显示在 JSP 页面中
- css - 在 Firefox 中渲染特殊字符
- python - 两个时间戳之间的差异四舍五入到数小时并将列添加到数据框
- curl - 卷曲创建一个大的帖子请求
- swift - 如何在 swift 4 中获取 CATextLayer 的“字符串”属性值?
- ios - 如何以编程方式将视图添加到合金中的滚动视图