当主视图导航到登录视图时,如何触发登录的 useEffect? [英] How can I do that when the home view navigates to the login view, trigger the useEffect of the login?
问题描述
基本上在 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?
推荐答案
clearStorage() 调用方法,当加载时.从 clearStorgae 中删除 ().
clearStorage() call the method, When If loaded. remove the () from clearStorgae.
<代码><Button onPress={clearStorage} ><Text>注销</Text></Button>
这篇关于当主视图导航到登录视图时,如何触发登录的 useEffect?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!