我希望每次执行名为login
的组件时,检测是否有保存的令牌的函数得到验证。login
我有一个函数来验证令牌是否存在,如果存在,则自动重定向到home
视图,否则它将保留在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....
因为令牌不再存在,因为它已被删除。
家
const Home= props => {
clearStorage = () => {
AsyncStorage.removeItem("token")
.then(() => {
props.navigation.navigate("Login");
})
};
return (
<View>
<Button onPress={clearStorage()} ><Text>Logout</Text></Button>
<View>
)
}
我该如何解决这个问题?
即使您删除了令牌,此更改也不会反映Login
组件中,因此loading
仍将true
,这就是不调用useEffect
的原因。尝试侦听组件上的didFocus
或willFocus
事件Login
并再次检查令牌是否存在
useEffect(()=>{
getTokenPrevious()
const focusListener = props.navigation.addListener('didFocus', () => {
getTokenPrevious()
})
return ()=>focusListener.remove()
},[])
而不是
useEffect(() => {
getTokenPrevious();
}, [loading]);