简体   繁体   English

React Native Firebase 应用程序:更改 Stack.Screen onAuthStateChange

[英]React Native Firebase App: Change Stack.Screen onAuthStateChange

I have a React-Native (sdk 46.0) Firebase app.我有一个 React-Native (sdk 46.0) Firebase 应用程序。 I want to make it so that when the user is signed in, he moves from the LoginScreen to to the HomeScreen.我想这样做,以便当用户登录时,他从登录屏幕移动到主屏幕。 Code is shown below.代码如下所示。

 // screens/LoginScreen.js >>... const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const navigation = useNavigation(); const handleLogin = () => { auth.signInWithEmailAndPassword(email, password).then((userCredentials) => { const user = userCredentials.user; console.log("Logged in with:", user.email); }).catch((error) => alert(error.message)); }; ... <View style={styles.inputContainer}> <Input style={styles.input} blurOnSubmit autoCorrect={false} placeholder="jdoe@ernestkoliqi.com" placeholderTextColor="#666" value={email} onChangeText={(text) => setEmail(text)} selectTextOnFocus keyboardType="email-address" /> <Input style={styles.input} blurOnSubmit autoCorrect={false} placeholder="Password" placeholderTextColor="#666" bool={true} value={password} onChangeText={(text) => setPassword(text)} selectTextOnFocus /> </View> <View style={styles.buttonContainerModal}> <TouchableOpacity onPress={handleLogin}> <View style={styles.ctaBtnModal}> <Text style={styles.loginBtn}>Log In</Text> </View> </TouchableOpacity>... // App.js... function Home() { return <HomeScreen />; } function News() { return <NewsScreen />; } function Calendar() { return <CalendarScreen />; } function Login() { return <LoginScreen />; } function Feed() { return ( <Tab.Navigator screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { let iconName; if (route.name === "Home") { iconName = focused? "home": "home-outline"; } else if (route.name === "News") { iconName = focused? "newspaper": "newspaper-outline"; } else if (route.name === "Calendar") { iconName = focused? "calendar": "calendar-outline"; } return <Ionicons name={iconName} size={size} color={color} />; }, activeTintColor: Colors.primary, inactiveTintColor: "gray", showLabel: true, showIcon: true, style: { paddingBottom: 4.25, paddingTop: 4.25, }, })} > <Tab.Screen name="Home" component={Home} options={{ headerShown: false }} /> <Tab.Screen name="Calendar" component={Calendar} options={{ headerShown: false }} /> <Tab.Screen name="News" component={News} options={{ headerShown: false }} /> </Tab.Navigator> ); } const Tab = createBottomTabNavigator(); const Stack = createNativeStackNavigator(); export default function App() { return ( <SafeAreaView style={styles.screen}> <StatusBar barStyle="light-content" translucent={true} /> <NavigationContainer theme={appTheme}> <Stack.Navigator> <Stack.Screen component={Login} options={{ headerShown: false }} name="Login" /> <Stack.Screen component={Feed} name="Feed" /> </Stack.Navigator> <LoginScreen /> </NavigationContainer> </SafeAreaView> ); }...

The code above shows the file structure and the code contained in the files relative to the topic.上面的代码显示了与主题相关的文件结构和文件中包含的代码。 How can I manage to change Stack.Screen when user==True?当 user==True 时,我如何设法更改 Stack.Screen?

You need a state that can be changed in the Login component.您需要一个可以在Login组件中更改的 state。 You could use a Context for this purpose.您可以为此目的使用Context

export const AppContext = React.createContext({});

export default function App() {

  const [isSignedIn, setIsSignedIn] = React.useState(false);
  const contextValue = React.useMemo(() => ({
      isSignedIn,
      setIsSignedIn
  }), [isSignedIn])

  return (
    <SafeAreaView style={styles.screen}>
      <StatusBar barStyle="light-content" translucent={true} />
      <AppContext.Provider value={contextValue}>
        <NavigationContainer theme={appTheme}>
          <Stack.Navigator>
           { 
             !isSignedIn ? (
               <Stack.Screen component={Login} options={{ headerShown: false }} name="Login" />
             ) : (
               <Stack.Screen component={Feed} name="Feed" />
             )
          </Stack.Navigator>
        </NavigationContainer>
      </AppContext.Provider>
    </SafeAreaView>
  );
}

The Login screen can access the context and change it if the user logs in successfully.如果用户成功登录, Login屏幕可以访问上下文并更改它。

const Login = (props) => {
    const { setIsSignedIn } = useContext(AppContext);

    const handleLogin = () => {
        auth
          .signInWithEmailAndPassword(email, password)
          .then((userCredentials) => {
             const user = userCredentials.user;
             console.log("Logged in with:", user.email);
             // success ? 
             setIsSignedIn(true);
           })
          .catch((error) => alert(error.message));
    };
    
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Native App:Email 地址验证 Firebase - React Native App: Email Address Verification Firebase React Native,堆栈导航组 Firebase 身份验证保持登录状态 - React Native, Stack Navigation Group for Firebase authentication stay logged in 在 React Native 的应用程序消息中安装 Firebase 时出错 - Error Installing Firebase In App Messaging in React Native 如何在 React 本机应用程序中过滤 Firebase Firestore Array 数据? - How to filter Firebase Firestore Array data in React native app? 如何在 React Native 应用程序上显示 firebase 存储中的所有图像? - How to display all images from firebase storage on React Native app? 如何在 React Native 应用程序中从 Firebase 实时数据库中获取数据 - How to Fetch Data from Firebase Realtime Database in React Native App 使用 firebase Crashlytics 进行 React Native 错误记录 - 如何获取 javascript 堆栈跟踪 - React Native error logging with firebase Crashlytics - How to get javascript stack trace 安装 react-native-firebase/app 后,Build 将在 react-native ios 中失败 - After installing react-native-firebase/app it's Build will failed in react-native ios React Native:从 firebase 导航到“嵌套在 BottomTabNavigator 内”的屏幕推送通知点击 - React Native : Navigate to a screen "nested inside BottomTabNavigator" from firebase push notificaiton click Firebase 是 react-native 后端 - Firebase are react-native backend
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM