【问题标题】:React Native pass data in all screenReact Native 在所有屏幕中传递数据
【发布时间】:2021-01-10 02:52:36
【问题描述】:

我想访问我所有屏幕中的一个对象。我通过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>
  );
}

【问题讨论】:

    标签: javascript firebase react-native firebase-authentication


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多