在所有屏幕上反应本机传递数据

时间:2020-09-23 20:34:23

标签: javascript firebase react-native firebase-authentication

我想访问所有屏幕上的对象。我通过firebase获得的用户对象。我从onAuthStateChanged方法获得对象。如何让用户进入app.js并在所有屏幕上都可以访问它?

多数民众赞成在根应用程序中的代码:

import React, { useEffect, useState } from 'react';
import { SafeAreaView, View, ActivityIndicator } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import AsyncStorage from '@react-native-community/async-storage';

import { globalStyles, styles } from './styles/global';
import BottomTabScreen, { RootStackScreen } from './navigation/Index';
import DrawerContent from './navigation/DrawerContent';

import { on_auth_state_changed } from './firebase/Api';

const Drawer = createDrawerNavigator();

export default function App() {

  const [authState, setAuthState] = useState({
    isAuthenticated: false,
    isAuthenticationReady: false,
    isLoadingComplete: false,
  });

  useEffect(() => {
    on_auth_state_changed(authStateChanged);
  }, [])

  function authStateChanged(user) {
    setAuthState({
      ...authState,
      isAuthenticated: !!user,
      isAuthenticationReady: true,
      isLoadingComplete: true,
    })
  }

  if (!authState.isLoadingComplete) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#80c904' }}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  return (
    <SafeAreaView style={globalStyles.container}>
      <NavigationContainer>
        {(authState.isAuthenticated) ?
          <Drawer.Navigator drawerContent={props => <DrawerContent {...props} />}>
            <Drawer.Screen name="HomeDrawer" component={BottomTabScreen} />
          </Drawer.Navigator>
          :
          <RootStackScreen />
        }
      </NavigationContainer>
    </SafeAreaView>
  );
}

1 个答案:

答案 0 :(得分:0)

您可以使用Context API来实现。还有其他选项,例如Redux或任何状态管理库,但对于您的需求,Context API绰绰有余。