首页 > 解决方案 > 如何从firebase正确显示表中的对象名称及其键

问题描述

我正在尝试通过在另一个映射函数中使用映射函数来显示我的数组,从而以表格格式正确显示来自 firebase 的对象名称及其键值。

    import React, { Component } from 'react';
    import { Text, View, ImageBackground, StyleSheet, ScrollView } from 'react-native';
    import CustomHeader from '../CustomHeader';
    import firebase from '../../database/firebase';
    import Schedule_1 from './Schedule_1';
    import Schedule_1_d from './Schedule_1_d';
    import { DataTable } from 'react-native-paper';
    
    var categories = []
    var categories1 = [];
    var data;
    export default class Bus_Schedule extends Component {
        constructor(props) {
            super(props);
            this.state = {
                dataArray: {},
                arrayList: [],
                menu1:[],
                menu2: [],
              };
    
        }
        componentDidMount() {
            firebase.database().ref('Schedule/Route-01/').on('value', querySnapShot => {
               data = querySnapShot.val() ? querySnapShot.val() : {};
    
               console.log("Data submit")
              let todoItems = {...data};
              console.log(todoItems);
              this.setState({
                dataArray: todoItems,
              });
            });
    
    
            ///
    
            // var data1 = [];
            // console.log("letter send");
            // firebase.database().ref('Schedule/Route-01/').once("value").then(snapshot => {
            //   var data1 = Object.keys(snapshot.val());
            //   console.log(data1);
              
            // })
            
            
    
            firebase.database().ref('Schedule/Route-01/').once('value').then(function(snapshot) {
    
              console.log("        Again");
    
              // this.setState({
              //   menu1: snapshot.val()
              // })
    
              // const categories = []
              // var categories1 = []
    
              snapshot.forEach(function(snap) {
                 const item = snap.val();
                  categories.push(item);
    
                const item1 = snap.key;
                  categories1.push(item1);
                
                  // Array1 = item;
                  // console.log(Array1);
                  // let item1 = snap.key ? snap.key : {};
                  // Array2 = item1;
                  
                 
                     
              });
    
              /// For object Values
            //   console.log("Values");
            //  console.log(categories);
            //   this.setState( {    //PASSING VARIABLE TO STATE
            //     menu1 :categories
            // })
            // console.log(this.state.menu1);
             /// For object Names
             console.log("Names");
            console.log(categories1);
              this.setState( {    //PASSING VARIABLE TO STATE
                menu2 :categories1
            })
            // console.log(this.state.menu2);
              
             
         }.bind(this));
    
          }
    
    
          empty()
          {
            categories1 = [];
            categories = [];
    
          }
          
        render() {
            let todosKeys = Object.keys(this.state.dataArray);
            
            return (
                <View
                style={styles.container}>
                <CustomHeader title="Bus Schedule" navigation={this.props.navigation} />
    
                <DataTable style={{ top: -12 }}>
                  <DataTable.Header style={{ backgroundColor: 'lightblue' }}>
                    <DataTable.Title style={{ justifyContent: 'center', alignItems: 'center' }}><Text style={{ fontSize: 20, fontWeight: "bold" }}>Route 1</Text></DataTable.Title>
    
                  </DataTable.Header>
                  
    ////Using map function inside a map function ///////
                  {categories1.map((item, key) => (
                    
                 
                  <View style={{ backgroundColor: '#D1FDFF' }} key ={key} id = {key}>
    
                    <DataTable.Row >
                      <DataTable.Cell style={{ marginLeft: 10 }}>
                      <Text style={{ fontSize: 15, fontWeight: "bold" }} key ={key} id = {key}>{item}
                      </Text>
                      
                      {categories.map((item1, key1) => (
                        <View style ={{flex:1, alignItems:'center', justifyContent:'center'}}  key ={key1} id = {key1}>
                          <Text  key ={key1} id = {key1} style ={{ marginLeft:5}}>{item1} </Text>
                          </View>
                      ))
                    }
    
                      </DataTable.Cell>
                      
                    </DataTable.Row>
    
                  </View>
                  )
                  )}
    
                </DataTable>

                {this.empty()}
              </View>
            );
        }
    }
    

    const styles = StyleSheet.create({
        container: {
            backgroundColor: '#FEF9E7',
            flex: 1,
        },
    
        appButtonText: {
            fontSize: 15,
            color: "#fff",
            fontWeight: "bold",
            alignSelf: "center",
            textTransform: "uppercase"
        }
    });

我正在尝试通过在另一个地图函数中使用地图函数以表格格式正确显示来自firebase的对象名称及其键值。但是我的表没有正确估价,我的出局如下所示。

在此处输入图像描述

输出

请点击查看我的输出

标签: javascriptfirebasereact-nativefirebase-realtime-database

解决方案


如果您只想key在右侧显示 和相应的值,则不需要两张地图。只需使用快照的keyandvalue()即可获取这两个数据。

更改这部分代码:

snapshot.forEach(function (snap) {
  const item = snap.val();
  categories.push({ key: snap.key, data: snap.val() });
});

这部分是:

{
  categories.map(({ key, data }, key) => (
    <View style={{ backgroundColor: "#D1FDFF" }} key={key} id={key}>
      <DataTable.Row>
        <DataTable.Cell style={{ marginLeft: 10 }}>
          <Text style={{ fontSize: 15, fontWeight: "bold" }} key={key} id={key}>
            {key}
          </Text>

          <View
            style={{
              flex: 1,
              alignItems: "center",
              justifyContent: "center",
            }}
            key={`key_1`}
            id={`key_1`}
          >
            <Text key={`key_2`} id={`key_2`} style={{ marginLeft: 5 }}>
              {data}
            </Text>
          </View>
        </DataTable.Cell>
      </DataTable.Row>
    </View>
  ));
}

推荐阅读