在React中导航屏幕时的白色屏幕

u2nhd7ah  于 2023-04-22  发布在  React
关注(0)|答案(1)|浏览(166)

所以最近,每当我尝试在react中导航到不同的屏幕时,我都会遇到一个问题。目前,我的代码旨在检测哪个用户角色已锁定(管理员和用户),但每当我以管理员身份登录并尝试访问管理员 Jmeter 板时,我都会得到一个白色屏幕。
App.js

import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import React, { useEffect, useState } from "react";
import { firebase, db } from './config'

import Login from './Screens/Login';
import Registration from './Screens/Registration';
import Dashboard from './Screens/Dashboard';
import UserDashboard from './Screens/UserDashboard';
import ProfileScreen from './Screens/Profile';
import JobScreen from './app/index';

import Header from './Header';

const Stack = createStackNavigator();

function App() {
    const [initializing, setInitializing] = useState(true);
    const [user, setUser] = useState(null);
    const [role, setRole] = useState(null);

    function onAuthStateChanged(user) {
        setUser(user);
        if (initializing) setInitializing(false);
    }

    useEffect(() => {
        const subscriber = firebase.auth().onAuthStateChanged(onAuthStateChanged);
        return subscriber;
    }, []);

    useEffect(() => {
        if (user) {
            const unsubscribe = firebase
                .firestore()
                .collection("users")
                .doc(user.uid)
                .onSnapshot((doc) => {
                    const userData = doc.data();
                    setRole(userData?.role);
                });
            return unsubscribe;
        }
    }, [user]);

    if (initializing) {
        return null; // or you can render a loading spinner here
    }

    if (!user) {
        return (
            <Stack.Navigator>
                <Stack.Screen
                    name="Login"
                    component={Login}
                    options={{
                        headerTitle: () => (
                            <Header name=" Welcome to the Industrial King " />
                        ),
                        headerStyle: {
                            height: 150,
                            borderBottomLeftRadius: 50,
                            borderBottomRightRadius: 50,
                            backgroundColor: "#00e4d0",
                            shadowColor: "#000",
                            elevation: 25,
                        },
                    }}
                />
                <Stack.Screen
                    name="Registration"
                    component={Registration}
                    options={{
                        headerTitle: () => (
                            <Header name="Please fill out all details below " />
                        ),
                        headerStyle: {
                            height: 150,
                            borderBottomLeftRadius: 50,
                            borderBottomRightRadius: 50,
                            backgroundColor: "#00e4d0",
                            shadowColor: "#000",
                            elevation: 25,
                        },
                    }}
                />
            </Stack.Navigator>
        );
    }

    switch (role) {
        case "admin":
            return (
                <Stack.Navigator>
                    <Stack.Screen
                        name="Dashboard"
                        component={Dashboard}
                        options={{
                            headerTitle: () => (
                                <Header name=" Admin Dashboard " />
                            ),
                            headerStyle: {
                                height: 150,
                                borderBottomLeftRadius: 50,
                                borderBottomRightRadius: 50,
                                backgroundColor: "#00e4d0",
                                shadowColor: "#000",
                                elevation: 25,
                            },
                        }}
                    />
                    <Stack.Screen
                        name="Profile"
                        component={ProfileScreen}
                        options={{
                            headerTitle: () => <Header name="Profile " />,
                            headerStyle: {
                                height: 150,
                                borderBottomLeftRadius: 50,
                                borderBottomRightRadius: 50,
                                backgroundColor: "#00e4d0",
                                shadowColor: "#000",
                                elevation: 25,
                            },
                        }}
                    />
                    <Stack.Screen name="Job" component={JobScreen} />
                </Stack.Navigator>
            );
        case "user":
            return (
                <Stack.Navigator>
                    <Stack.Screen
                        name="UserDashboard"
                        component={UserDashboard}
                        options={{
                            headerTitle: () => <Header name="Profile " />,
                            headerStyle: {
                                height: 150,
                                borderBottomLeftRadius: 50,
                                borderBottomRightRadius: 50,
                                backgroundColor: "#00e4d0",
                                shadowColor: "#000",
                                elevation: 25,
                            },
                        }}
                    />
                </Stack.Navigator>
            );
        default:
            return null;
    }
}

export default () => {
    return (
        <NavigationContainer independent={true}>
            <App />
        </NavigationContainer>

    );
}

Dashboard.js

import React, { useEffect, useState } from "react";
import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native';
import { SafeAreaView } from "react-native-safe-area-context";
import { firebase } from '../config';
import { useNavigation } from '@react-navigation/native';

const Dashboard = () => {
    const [name, setName] = useState('')
    const navigation = useNavigation();

    //Change Users Password
    const changePassword = () => {
        firebase.auth().sendPasswordResetEmail(firebase.auth().currentUser.email)
        .then(() => {
            alert("Password reset email")
        }).catch((error) => {
            alert(error)
        })
    }

    useEffect(() => {
        firebase.firestore().collection('users')
        .doc(firebase.auth().currentUser.uid).get()
        .then((snapshot) => {
            if (snapshot.exists) {
                setName(snapshot.data())
            } else {
                console.log('User does not exist')
            }
        })
    }, [])

    return (
        <SafeAreaView>
            <TouchableOpacity
                onPress={() => {
                changePassword()
                }}>
            </TouchableOpacity>

            <TouchableOpacity
                onPress={() => navigation.navigate('index')}
                style={styles.button}>
                <Text style={{ fontSize: 22, fontWeight: 'bold' }}>
                    Search for Jobs
                </Text>
            </TouchableOpacity>

            <TouchableOpacity
                onPress={() => navigation.navigate('Profile')}
                style={styles.button}>
                <Text style={{ fontSize: 22, fontWeight: 'bold' }}>
                    View Profile
                </Text>
            </TouchableOpacity>
            <TouchableOpacity
                onPress={() => { firebase.auth().signOut() }}
                style={styles.button}>
                <Text style={{ fontSize: 22, fontWeight: 'bold' }}>
                    Sign out
                </Text>
            </TouchableOpacity>
        </SafeAreaView>
    )
}

export default Dashboard

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        marginTop: 100,
    },
    button: {
        marginTop: 50,
        height: 70,
        width: 250,
        backgroundColor: '#026efd',
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 50,
    }
})

Firebase.Config

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
    apiKey: "AIzaSyAMTzGwM8KlZdKhk4EowjlaOgLaeDBnBDU",
    authDomain: "honsprojectfinal.firebaseapp.com",
    databaseURL: "https://honsprojectfinal-default-rtdb.asia-southeast1.firebasedatabase.app",
    projectId: "honsprojectfinal",
    storageBucket: "honsprojectfinal.appspot.com",
    messagingSenderId: "214071266814",
    appId: "1:214071266814:web:f4cbe25a3e124ca8a044af",
    measurementId: "G-TVF8SE9809"
};

if (!firebase.apps.length){
    firebase.initializeApp(firebaseConfig);
}

const db = firebase.firestore();

// Add a new collection to store user roles
const rolesRef = db.collection('roles');

export { firebase, db, rolesRef };
ktecyv1j

ktecyv1j1#

我建议你验证initializing的状态,也许你正在执行第48行的if (initializing)。在第93行的switch上验证case上的role值,也许它正在执行default case和return null

相关问题