首页 > 解决方案 > 每次在本机反应中重新渲染组件或在屏幕显示上调用函数

问题描述

我想在我的应用程序中实现注销功能,并且我的注销菜单正在使用抽屉导航菜单出现。当我第一次单击注销菜单时,我在注销组件 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;

标签: react-native

解决方案


首先,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");
  }, []));

推荐阅读