React Native:登录或注销时如何以编程方式刷新应用程序?
Posted
技术标签:
【中文标题】React Native:登录或注销时如何以编程方式刷新应用程序?【英文标题】:React Native: How to make app programatically refresh when signing in or out? 【发布时间】:2021-05-27 19:10:26 【问题描述】:我的应用使用 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;
【问题讨论】:
【参考方案1】:您愿意重新渲染您的组件。 满足您需求的东西是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")
)
【讨论】:
以上是关于React Native:登录或注销时如何以编程方式刷新应用程序?的主要内容,如果未能解决你的问题,请参考以下文章
react-native如何在facebook登录和注销后刷新页面
无法注销。基于 Auth0 的 React Native Expo 应用程序