reactjs - 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;
解决方案
您愿意重新渲染您的组件。满足您需求的东西是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")
}
})
推荐阅读
- flutter - Flutter:来自 CollectionReference 的 Firestore 查询
- javascript - 带滚动和半页固定的半页垂直滑块
- android - 如何在 Unity 画布上绘制 android 视图?
- c# - 将德国货币字符串解析为十进制
- python - 如何使用 Pulp python 优化字典中的变量组合?
- android - "code":"BAD_REQUEST_ERROR","description":"提供的 id 不存在" RazorPay 集成到 android 时出错
- angular6 - Angular 中是否有可用的 ace.js 组件,它也可以用作 FormControl
- c++ - 如何在调用原始方法之前覆盖全局方法名称以将我的代码推送到前面
- python - Python 用条件断言
- android - 通过拖动更改项目位置后保存recyclerview