首页 > 解决方案 > React Native:登录或注销时如何以编程方式刷新应用程序?

问题描述

我的应用程序使用 Expo 和 React Native。我已经使用 Firebase 实现了身份验证。

我的问题是,当我登录或注销时,导航堆栈应该会更改,但不会刷新。唯一的方法是如果我更改代码并且 Expo 实现快速刷新。当身份验证状态更改但由于某种原因 NavigationContainer 没有更改时,控制台日志会打印。无论如何,我可以以编程方式创建快速刷新吗?

这是我的代码:

// App.js
import React from 'react';
import { StyleSheet, Text, TouchableOpacityComponent, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import AuthStackScreen from './screens/AuthStack/AuthStackScreen';
import AppStackScreen from './screens/AppStack/AppStackScreen';
import Firebase from './firebase/Firebase';


const App = () => {
  let loggedIn;

  if(Firebase.auth().currentUser) {
    loggedIn = true;
  }

  Firebase.auth().onAuthStateChanged(user => {
    if(user) {
      loggedIn = true;
      console.log("logged in")
    } else {
      loggedIn = false;
      console.log("logged out")
    }
  })

  return (
    <NavigationContainer>
      { loggedIn ? <AppStackScreen/> : <AuthStackScreen/> }
    </NavigationContainer>
  )
  
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

标签: reactjsreact-nativefirebase-authenticationexpo

解决方案


您愿意重新渲染您的组件。满足您需求的东西是Hooks

基本上你应该转换你的

 let loggedIn;

进入

 const [loggedIn,setLoggedIn]=useState(false)
      if(Firebase.auth().currentUser) {
         setLoggedIn(true)
       }
      Firebase.auth().onAuthStateChanged(user => {
         if(user) {
           setLoggedIn(true)
           console.log("logged in")
         } else {
           setLoggedIn(false)
           console.log("logged out")
         }
       })

推荐阅读