如何使用 useState 使函数在每次进入组件时运行?



我希望每次执行名为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的原因。尝试侦听组件上的didFocuswillFocus事件Login并再次检查令牌是否存在

useEffect(()=>{
getTokenPrevious()
const focusListener = props.navigation.addListener('didFocus', () => {
getTokenPrevious()
})
return ()=>focusListener.remove()
},[])

而不是

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

最新更新