Firebase在React Native数据提取中返回“未定义”值

时间:2019-12-13 05:05:52

标签: javascript reactjs firebase react-native firebase-realtime-database

我正在尝试从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})
  });
}

Firebase上的数据结构如下-
Firebase data


数组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项。

1 个答案:

答案 0 :(得分:2)

尝试以下操作:

getData(){
  firebase.database().ref('Restaurants/').on("value", snapshot =>{
  snapshot.forEach((childSub) => {
    let key = childSub.key;
    let restaurantList = childSub.val();
    console.log(restaurantList);
   });
  });
}

未定义的键是密钥,请尝试在键内部进行迭代并检索数据