使用React Native的Firebase查询未在我的屏幕上显示(但在console.log上显示)

问题描述 投票:1回答:1

我的数据按预期显示在console.log上,但不在我的屏幕上。这是控制台日志的屏幕截图。

enter image description here

这是我的代码:

componentWillMount = () => {
this.getData();
}

getData(){
  const { currentUser } = firebase.auth();
    firebase
    .database()
    .ref(`/users/${currentUser.uid}/data/`)
    .orderByKey()
    .on('child_added', snap =>  {

      //Is this correct or does it need to be formatted a different way?
      snap.key, 
      snap.val().Weight 

      //note that the console logs below displays the data
      console.log(snap.key)
      console.log(snap.val().Weight)

    }) 
}

renderRow = () => {
  return (
    <View style={[styles.card, styles.cardBorderTop]}>
      <Text>
        {snap.key} //Is this the correct way to reference this value?
      </Text>
      <Text style={[styles.textRight]}>
        {snap.val().Weight} //Is this the correct way to reference this value?
      </Text>
    </View>
  )
}

  render() {
    return (
      <View style={[styles.container]}>
        <FlatList
          data={this.getData} //Is this the correct data reference?
          renderItem={this.renderRow} 
        />
      </View>
    );
  }
}

这就是我的屏幕渲染方式。请注意,我期望数据在FlatList上呈现。 enter image description here

任何帮助将不胜感激。

在旁注中,我现在意识到我需要将日期存储为ISO-8601,因此它们可以正确排序,在我弄清楚如何在屏幕上呈现查询数据后,我将会这样做。

更新我意识到我的问题不像我预期的那样清晰,我为此道歉。我需要的是能够通过日期键和Weight子查询我的数据。我能够使用snap.key和snap.val()成功地做到这一点。控制台上的重量,但它看起来不像是在我的FlatList上显示数据所需的正确引用,这就是我需要帮助的地方。

作为参考,这是我的Firebase数据库:enter image description here

javascript firebase react-native firebase-realtime-database
1个回答
1
投票

你的getData函数目前没有返回任何东西,所以虽然视图可能会调用getData()但它没有任何回报。

但是简单地添加return语句将无济于事,因为数据是异步加载的。在React中,您应该将数据置于组件的状态(通过调用setState()),然后在渲染器中使用它。

在代码中:

componentWillMount = () => {
  this.setState({ data: [] });
  this.getData();
}

getData(){
  const { currentUser } = firebase.auth();
  firebase
    .database()
    .ref(`/users/${currentUser.uid}/data/`)
    .orderByKey()
    .on('child_added', snap =>  {
      var data = this.state.data;
      data.push({ key: snap.key, weight: snap.val().Weight });
      this.setState({ data: data });
    }) 
}

所以这:

  • 将状态中的data属性初始化为空数组。
  • 将每个新项添加到data,因为它来自数据库。

有了这个,您可以使用以下方式呈现数据数组:

renderRow = ({item}) => {
  return ( 
    <View style={[styles.card, styles.cardBorderTop]}> 
      <Text> 
        {item.key} 
      </Text> 
      <Text style={[styles.textRight]}>
        {item.Weight} 
      </Text>
    </View>
  )
}

render() {
  return (
    <View style={[styles.container]}>
      <FlatList
        data={this.state.data}
        renderItem={this.renderRow} 
      />
    </View>
  );
}

最后一位可能包含语法错误,因为我从未使用过FlatList。如有疑问,请与后者here的文档进行比较。

© www.soinside.com 2019 - 2024. All rights reserved.