遍历数据库子项并显示每个子项

时间:2019-06-15 06:09:11

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

我有这段代码可以显示一个孩子,但是是否可以遍历所有孩子并一次显示所有孩子?这是我的Firebase数据库image link的结构,关于如何执行此操作的任何信息都将非常有用,我已经阅读了有关映射数据(如JSON)的信息,但是当涉及通过前端解析代码时,奋斗了很多。谢谢!

import React, { Component } from 'react';
import styles from './Styles.js';
import {
  Text,
  View,
  Image,
  Button,
  TouchableOpacity,
  Dimensions,
  ScrollView,
  StatusBar,
} from 'react-native';
import { LinearGradient } from 'expo';
import * as firebase from 'firebase';

export class Dog extends Component {

    componentDidMount(){
      firebase.database().ref('pets/1').once('value', (snapshot) => {''
      const snap = snapshot.val();
          this.setState({ 
            name: snap.name,
            petlocation: snap.location,
            type: snap.type,
            reward: snap.reward,
            time: snap.time,
            phone: snap.phone
          })
      });
    }

  constructor(props) {
    super(props);

    this.state = {
        pets: {
          name: '',
          petlocation: '',
          type: '',
          reward: '',
          time: '',
          phone: null,
      }
    };
  }

  render() {
    return (
      <View style={styles.locpetinfo}>
                <Image style={styles.locpetimg} source={require('assets/dog.jpg')} />
                <Text style={styles.locpetname}>{this.state.name}</Text>
                <Text style={styles.locpetpos}>{this.state.petlocation}</Text>
                <Text style={styles.locpettype}>{this.state.type}</Text>
                <Text style={styles.loctime}>{this.state.time}</Text>
                <Text style={styles.locbounty}>{this.state.reward}</Text>
                <Text style={styles.locbountysub}>REWARD</Text>
              </View>
    );
  }
}

export default Dog;

2 个答案:

答案 0 :(得分:1)

将快照值保存到状态。

.l

或没有异步/等待

componentDidMount = async () => {

  await firebase.database().ref('pets').once('value', (snapshot) => {
    this.setState({ data: [].concat.apply([], snapshot.val()) });
  });
}

答案 1 :(得分:0)

@rbxnt,您可以将快照存储在数组中,并可以如下所示显示快照

let pets = [];

const snap = snapshot.val();
firebase.database().ref('pets').once('value, (snapshot) => {
 pets.push(snap);
});