当主页视图导航到登录视图时,如何触发登录的useEffect?

2023-12-04

基本上在login我有一个函数可以验证令牌是否存在,如果存在则自动重定向到home视图,否则它将保留在login view.

Login

const Login = props => {
   const [loading, setLoading] = useState(true); 

   useEffect(() => {
    getTokenPrevious();
   }, [loading]);


    const getTokenPrevious = () => {
    AsyncStorage.multiGet(["token"])
        .then(value => {
            let token = value[0][1];

            if (token !== null) {
                props.navigation.navigate("home");
            } else {
                setLoading(false);
            }
        })
        .catch(error => {
            setLoading(false);
        });
   };


   if (loading) {
        return (
            <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
                <Text>Loading...</Text>
                <Spinner color={STYLES.bgHeader.backgroundColor} />
            </View>
        );
    }

  return (
    rest code login....

有时当从home查看我使用的backbutton或当我尝试点击手机时logout按钮,这会将我重定向到login查看但这部分显示:

        return (
            <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
                <Text>Loading...</Text>
                <Spinner color={STYLES.bgHeader.backgroundColor} />
            </View>
        );

应该显示的部分是这样的:

  return (
    rest code login....

因为令牌已被删除而不再存在。

home

const Home= props => {

 clearStorage = () => {
 AsyncStorage.removeItem("token")
  .then(() => {
    props.navigation.navigate("Login");
  })

 };

 return (
 <View>
  <Button onPress={clearStorage()} ><Text>Logout</Text></Button>
 <View>
 )
}

我怎样才能解决这个问题?


<Button onPress={clearStorage()} ><Text>Logout</Text></Button>

如果加载的话,clearStorage() 会调用该方法。 从clearStorgae 中删除()。

<Button onPress={clearStorage} ><Text>Logout</Text></Button>

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当主页视图导航到登录视图时,如何触发登录的useEffect? 的相关文章

随机推荐