react-native - 每次在本机反应中重新渲染组件或在屏幕显示上调用函数
问题描述
我想在我的应用程序中实现注销功能,并且我的注销菜单正在使用抽屉导航菜单出现。当我第一次单击注销菜单时,我在注销组件 useeffect 挂钩中编写的代码正在运行并重定向到登录页面但是从第二次开始它就不起作用了,因为没有调用 useEffect 函数。当我的注销屏幕出现在屏幕上时,如何每次运行该函数。我的注销组件代码是这样的。
import React,{ useState,useEffect,useCallback } from "react";
import { View,StyleSheet,ActivityIndicator,AsyncStorage} from "react-native";
import GenericAPICall from "../WebUtils/GenericAPICall";
const Logout=({navigation})=>{
const[isVisible,setVisible]=useState(true);
removeSession=()=>{
console.log('session');
var magToken=AsyncStorage.getItem('magtoken');
AsyncStorage.removeItem('magtoken');
AsyncStorage.setItem('isloggedin', "false");
navigation.navigate("Login");
setVisible(false);
}
useEffect(() => removeSession(),[]);
return(
<View style={styles.container}>
<ActivityIndicator animating={isVisible} size="large" color="#0000ff" />
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
}
})
export default Logout;
解决方案
首先,AsyncStore 是异步函数,你应该修改removeSession
函数。
removeSession= async ()=>{
console.log('session');
if(isVisible){
navigation.navigate("Login");
}
// it is uselesss
// var magToken= await AsyncStorage.getItem('magtoken');
await AsyncStorage.removeItem('magtoken');
await AsyncStorage.setItem('isloggedin', "false");
setVisible(false);
}
其次,如果您使用导航进入注销屏幕。第二次,它没有重新安装。您可以更改为使用导航生命周期方法。那么您可能需要将其更改为组件或使用`react-native-hooks
useFocusEffect(useCallback(() => {
console.debug("screen takes focus");
removeSession()
return () => console.debug("screen loses focus");
}, []));
推荐阅读
- google-api - 如何获取对所有用户都有效的 Google Workspace 帐户的访问令牌
- spring - Wiremock - 有时它会抛出“软件导致连接中止:recv failed”
- google-sheets - (谷歌表格)例外:范围内的行数必须至少为 1
- mysql - MySQL时间范围不包括重叠时间范围
- bash - 使用 bash 计算字符串的出现次数后输出 IP 地址和执行命令
- pdf - 如何在 Epson TM-m30II 中打印从碧玉报告导出的 pdf?
- apache-spark - 如何修复 Apache Livy LDAP 身份验证错误?
- r - 使用 R 中的条件替换列值
- dependencies - 符合 UML 的图表或替代方案来说明项目依赖关系
- selenium - 即使驱动程序兼容,Chrome 更新到版本 92 也会引发异常