完成Firebase数据库拉取之前的React Native(Expo)渲染页面

时间:2020-04-10 04:40:14

标签: firebase react-native expo

因此,我试图从Firebase数据库中提取一些数据,然后将其显示在屏幕上,以供配置文件页面使用(对于正在进行的应用程序),所以请原谅我现在编码混乱。

我已经尝试了异步功能,当我在其他页面上执行此操作时似乎工作正常,但是它将始终在数据库提取完成之前呈现页面

如果您需要更多信息,我非常愿意为您提供信息!

这是我的代码:

import React, { Component } from 'react';
import { View, KeyboardAvoidingView, ActivityIndicator, Dimensions, ScrollView, Text, StyleSheet, Switch, TouchableOpacity, Image, Alert, prompt, Modal } from 'react-native';
import firebase from './firebase';
import { TextInput } from 'react-native-gesture-handler';
import DialogInput from 'react-native-dialog-input';
const { width, height } = Dimensions.get('window');

// const firebase = firebase.database();
console.disableYellowBox = true;



export default class Profile extends Component {
    state = { loaded: null, username: null, bio: null, currentUser: null, changeUsername: '', changed: null, errorMessage: null, publicEventsOnScreen: {} }



    componentWillMount() {
        const { currentUser } = firebase.auth()
        this.getUsername(currentUser)
        this.props.navigation.setParams({ title: this.state.username });

    }


    componentDidMount() {
        this._navListener = this.props.navigation.addListener('willFocus', () => {
            // this.setState({ username: 'user' });
            // get your new data here and then set state it will rerender
            const { currentUser } = firebase.auth()
            this.setState({ currentUser })
            this.setState({ errorMessage: null })

            firebase.auth().onAuthStateChanged(user => {
                console.log()
                this.props.navigation.navigate(user ? 'tabs' : 'LoginScreen')
            })
            this.getUsername(currentUser)

            this.state.username == null ? null : this.getUsername()



        });

        const { currentUser } = firebase.auth()
        this.setState({ currentUser })
        console.log("USER ID: " + currentUser.uid);



    }

    getUsername = async (test) => {
        const { currentUser } = firebase.auth()
        var data = await {};
        firebase.database().ref('users/' + currentUser.uid).on('value', (snapshot) => {
            console.log(snapshot.val())
            data = snapshot.val();
        });
        let username = await data.username;
        let bio = await data.bio;
        this.setState({ username, bio });
        this.setState({ changeUsername: this.state.username })
    }

    changeUsername = () => {
        this.setState({ changed: null, errorMessage: null })
        console.log("New Username: " + this.state.changeUsername);
        var removeSpaceUsername = this.state.changeUsername.replace(/\s+/g, '_');
        this.setState({ changeUsername: removeSpaceUsername })
        firebase.database().ref().child(`users`).orderByChild('usernamelowercase').equalTo(removeSpaceUsername.toLowerCase()).once("value", snapshot => {
            if (snapshot.exists()) {
                this.setState({ userData: this.state.username, errorMessage: "Username is already taken." }, function () {
                    console.log("running... :/ VALUES: " + JSON.stringify(snapshot.val()))

                })
                userData = true
                console.log("user entered: " + this.state.username + " errormessage: " + this.state.errorMessage);
            }
            else if (this.state.changeUsername == '') {
                console.log("username empty!");
                this.setState({ errorMessage: 'You cannot leave this field blank!' })
            }
            else {
                console.log('nothing found.?');
                this.setState({ userData: null })
                this.continueUsernameChange()
            }
        })
            .catch(() => {
                console.log('error')
            });



    }

    continueUsernameChange() {
        this.setState({ errorMessage: null })
        firebase.database().ref('users/' + firebase.auth().currentUser.uid + '/').update({
            username: this.state.changeUsername,
            usernamelowercase: this.state.changeUsername.toLowerCase()
        })
            .catch(error => this.setState({ errorMessage: error.message }))
        // if (this.state.errorMessage == '') {
        this.setState({ changed: 'Username Succesfully Changed.' })
        // }
    }


    categoryPress = (category) => {
        console.log(category);
        this.props.navigation.push('ProfilePEEventsScreen', { selectedCategory: category })
    }



    render() {




        return (
            <View style={styles.container}>
                <TouchableOpacity style={styles.pfpContainer}>
                    <Image source={require('./assets/N6Icon.jpeg')} style={styles.pfp} />
                </TouchableOpacity>
                <TouchableOpacity style={styles.editProfile}>
                    <Text style={styles.editPFTXT}>Edit Profile</Text>
                </TouchableOpacity>
                <Text style={styles.title}>{this.state.username == null ? "Loading..." : this.state.username}</Text>

                <View style={styles.profile}>
                    <Text>{this.state.bio == null ? "Loading..." : this.state.bio}</Text>
                </View>



                {/* <KeyboardAvoidingView style={styles.avoidingContainer} behavior="padding">


                    {this.state.changed &&
                        <Text style={{ color: 'green' }}>
                            {this.state.changed}
                        </Text>}
                    {this.state.errorMessage &&
                        <Text style={{ color: 'red' }}>
                            {this.state.errorMessage}
                        </Text>}

                    <TextInput
                        style={styles.textInput}
                        autoCapitalize="none"
                        placeholder="enter new username..."
                        placeholderTextColor="black"
                        onChangeText={changeUsername => this.setState({ changeUsername })}
                        value={this.state.changeUsername}
                        onFocus={() => this.setState({ changeUsername: this.state.username })}
                    />
                    <TouchableOpacity style={styles.button}
                        title="Change Username" onPress={this.changeUsername} >
                        <Text style={{ fontWeight: 'bold', textAlign: 'center' }}>Change Username</Text>
                    </TouchableOpacity>

                </KeyboardAvoidingView> */}

            </View>


        );
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        top: 0,
    },
    avoidingContainer: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        // top: 50,
        position: 'absolute',
        paddingBottom: 30,

    },
    divider: {
        borderBottomWidth: 2,
        width: '100%',
        marginBottom: 20,
        paddingBottom: 20,
        top: 200,
        position: 'absolute',
        zIndex: 100000,
    },
    titleText: {
        fontSize: 30,
    },
    padding: {
        padding: 10,
    },
    TextInput: {
        backgroundColor: 'grey',
        height: 20,
        width: '100%',
        marginBottom: 30,
        textAlign: "center"
    },
    title: {
        fontSize: 30,
        top: 15,
        right: 15,
        position: "absolute",
        width: width * 0.70,
        textAlign: 'center',
    },
    textInput: {
        height: 40,
        width: width - 50,
        borderColor: 'black',
        borderRadius: 10,
        backgroundColor: 'rgba(255,255,255, 0.5)',
        borderWidth: 1,
        borderWidth: 1,
        margin: 5,
        padding: 7,
        marginTop: 8,
    },
    button: {
        backgroundColor: "green",
        padding: 15,
        // backgroundColor: 'rgba(0,0,0, 0.1)',
        borderWidth: 1,
        borderRadius: 10,
        marginTop: 5,
        width: width - 50,
        // top: 20,
    },
    scrollView: {
        // zIndex: 10000,
        top: 100,
    },
    event: {
        margin: 15,
        backgroundColor: 'lightgrey',
        borderWidth: 1,
        borderRadius: 10,
        width: width - 50,
        height: 100,
        paddingLeft: 10,
        paddingTop: 10,
        alignSelf: 'center'
    },
    eventRemove: {
        width: 150,
        padding: 5,
        borderWidth: 1,
        borderRadius: 5,
        backgroundColor: 'red',
        marginTop: 10,

    },
    eventRemoveText: {
        alignSelf: 'center',
    },
    buttons: {
        bottom: 0,
        marginTop: 5,
        position: 'absolute',
        marginBottom: 50,
    },
    pfp: {
        width: width * 0.25,
        height: width * 0.25,
        borderRadius: (width * 0.25)/2,
    },
    pfpContainer: {
        position: 'absolute',
        left: 15,
        top: 15,
        borderRadius: (width * 0.25)/2,
        borderColor: 'black',
    },
    editProfile: {
        marginTop: 10,
        position: 'absolute',
        top: 45,
        right: 15,
        width: width * 0.65,
        height: (width * 0.25) - 40,
        borderRadius: 5,
        borderWidth: 1,
        alignItems: 'center',
        flex: 1,
        justifyContent: 'center',


    },
    editPFTXT: {

        // padding: 15,
        textAlign: 'center',
        textAlignVertical: 'center',

    },
    profile: {
        position: 'absolute',
        top: width * 0.30,
        width: width*0.9
    }
});

0 个答案:

没有答案