我正在尝试从Firebase实时数据库中获取餐厅列表,
我的代码因获取数据而被剪短-
_isMounted = false;
state :{
data: [],
}
constructor(props){
super(props)
this.state = {
data:[],
}
}
componentDidMount(){
this._isMounted = true
this.getData()
}
componentWillUnmount(){
this._isMounted = false
}
getData(){
firebase.database().ref('Restaurants/').on("value", snapshot =>{
let restaurantList = snapshot.val();
console.log(restaurantList)
this.setState({data: restaurantList})
});
}
数组restaurantList
的控制台输出为-
Array [
undefined,
Object {
"location": "Testing data",
"name": "Time Traveller",
"rating": 4.5,
"tags": "Indian, Asian",
},
Object {
"locations": "Testing data",
"name": "Novelty",
"rating": 4.5,
"tags": "Indian",
},
]
我不确定要从何处获得数组中的undefined
项。
答案 0 :(得分:2)
尝试以下操作:
getData(){
firebase.database().ref('Restaurants/').on("value", snapshot =>{
snapshot.forEach((childSub) => {
let key = childSub.key;
let restaurantList = childSub.val();
console.log(restaurantList);
});
});
}
未定义的键是密钥,请尝试在键内部进行迭代并检索数据