当主视图导航到登录视图时,如何触发登录的 useEffect? [英] How can I do that when the home view navigates to the login view, trigger the useEffect of the login?

查看:33
本文介绍了当主视图导航到登录视图时,如何触发登录的 useEffect?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically in login I have a function that verifies if a token exists, and if it exists automatically redirects to thehome view, otherwise it will remain in the login view.

登录

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 视图,但这部分显示:

Sometimes when from the home view I use thebackbutton of the cell phone or when I try to tap on the logout button, this redirects me to thelogin view but this part is shown:

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

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

the part that should be shown is this:

  return (
    rest code login....

因为令牌不再存在,因为它被删除了.

because the token no longer exists because it was deleted.

const Home= props => {

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

 };

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

我该如何解决这个问题?

How can i fix this?

推荐答案

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆