0

我想在React Native的Listview中顯示來自Firebase的數據。React Native - Firebase with ListView

我成功顯示「嘿」這樣的靜態數據,但我不知道如何顯示Firebase數據。我的數據庫是這樣的:用戶>電子郵件(例如爲了顯示電子郵件)。

我沒有firebaseConfig和兩個.js文件:

  1. index.ios.js:

代碼:

import React, { Component } from 'react'; 
import { AppRegistry, View, ListView, StyleSheet, Text } from 'react-native'; 
import Row from './Row'; 
import * as firebase from 'firebase'; 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    marginTop: 20, 
    }, 
    separator: { 
    flex: 1, 
    height: StyleSheet.hairlineWidth, 
    backgroundColor: '#8E8E8E', 
    }, 
}); 

// Initialize Firebase 
const firebaseConfig = { 
    apiKey: "xx", 
    authDomain: "xx", 
    databaseURL: "xx", 
    storageBucket: "<your-storage-bucket>", 
}; 
const firebaseApp = firebase.initializeApp(firebaseConfig); 

export default class App extends Component { 
    constructor(props) { 
    super(props); 

    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); 
    this.state = { 
     dataSource: ds.cloneWithRows(['row 1', 'row 2']), 
    }; 
    } 

    render() { 
    return (
     <ListView 
     style={styles.container} 
     dataSource={this.state.dataSource} 
     renderRow={(data) => <Row {...data} />} 
     renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />} 
     /> 
    ); 
    } 
} 

AppRegistry.registerComponent('App',() => App); 
  • 行.js:
  • 代碼:

    import React from 'react'; 
    import { View, Text, StyleSheet, Image } from 'react-native'; 
    
    const styles = StyleSheet.create({ 
        container: { 
        flex: 1, 
        padding: 12, 
        flexDirection: 'row', 
        alignItems: 'center', 
        }, 
        text: { 
        marginLeft: 12, 
        fontSize: 16, 
        }, 
    }); 
    
    const Row = (props) => (
        <View style={styles.container}> 
        <Text style={styles.text}> 
        "Hey" 
        </Text> 
        </View> 
    ); 
    
    export default Row; 
    

    回答

    0

    首先,您需要爲您的數據提取/查詢firebase。這通常在構造函數或componentWillMount生命週期方法中完成。沿線的

    東西:

    firebaseApp.database().ref().child(`${<someUserPath>}/username`).once("value", (snapshot) => { 
        this.setState({ username: snapshot.val() }); 
        }); 
    

    之後,你有你想要的數據,然後傳下來的ListView道具這樣的:

    <ListView 
        dataSource={this.state.dataSource.cloneWithRows([this.state.username])} />