【问题标题】:Looping through database children and displaying each循环访问数据库子项并显示每个子项
【发布时间】:2019-10-29 15:52:11
【问题描述】:

我有这段代码用于显示一个孩子,但是否可以遍历所有孩子并一次显示全部?这是我的 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;

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      将快照值保存到状态中。

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

      或者没有异步/等待

      componentDidMount = () => {
      
        const petsRef = firebase.database().ref();
      
          petsRef
          .child('pets')
          .once('value')
          .then(snapshot => {
            this.setState({ data: [].concat.apply([], snapshot.val()) });
          })
          .catch(e => console.log(e))
      
      }
      

      【讨论】:

      • 是的,你是个传奇!谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      相关资源
      最近更新 更多