对不活动的本机注销进行反应



我必须制作一个react原生应用程序(既不使用expo也不使用hook(,它可以登录到用户,读取一些简单的信息,然后通过注销按钮注销,或者由于不活动而自动注销。

我对登录、设置计时器或注销按钮都没有问题,但我不知道如何检测"不活动",这可能与状态有关吗?具体是怎么回事?

一般的共识似乎是使用PanResponder:

在react本机中获取用户不活动

检查React Native应用中的不活动

state = {};
_lastInteraction = new Date();
_panResponder = {};
componentWillMount() {
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: this.handleStartShouldSetPanResponder,
onMoveShouldSetPanResponder: this.handleMoveShouldSetPanResponder,
onStartShouldSetPanResponderCapture: () => false,
onMoveShouldSetPanResponderCapture: () => false,
onPanResponderTerminationRequest: () => true,
onShouldBlockNativeResponder: () => false,
});
this._maybeStartWatchingForInactivity();
}
_maybeStartWatchingForInactivity = () => {
if (this._inactivityTimer) {
return;
}
this._inactivityTimer = setInterval(() => {
if (
new Date() - this._lastInteraction >= TIME_TO_WAIT_FOR_INACTIVITY_MS
) {
this._setIsInactive();
}
}, INACTIVITY_CHECK_INTERVAL_MS);
};
// NOTE: you almost certainly want to throttle this so it only fires
// every second or so!
_setIsActive = () => {
this._lastInteraction = new Date();
if (this.state.timeWentInactive) {
this.setState({ timeWentInactive: null });
}
this._maybeStartWatchingForInactivity();
};
_setIsInactive = () => {
this.setState({ timeWentInactive: new Date() });
clearInterval(this._inactivityTimer);
this._inactivityTimer = null;
};
render() {
return (
<View
style={styles.container}
collapsable={false}
{...this._panResponder.panHandlers}>
<Text style={styles.paragraph}>
Put your app here
{' '}
{this.state.timeWentInactive &&
`(inactive at: ${this.state.timeWentInactive})`}
</Text>
<Button
title="Here is a button for some reason"
onPress={() => alert('hi')}
/>
</View>
);

您可以使用import AsyncStorage from '@react-native-async-storage/async-storage';

所以基本上,每当用户访问应用程序时,你都可以存储用户登录的时间

像这个

const storeData = async (value) => {
try {
await AsyncStorage.setItem('@last_visited', new Date().toString())
} catch (e) {
// saving error
}
}

然后,当用户再次回来访问该应用程序时,您可以检查该时间与异步存储中存储的时间之间的差异。

第一个

const getData = async () => {
try {
const value = await AsyncStorage.getItem('@last_visited')
if(value !== null) {
if(new Date() - value > 5){
// here check if time diff is what as per you is inactive then logout user
// for example ive kept 5 hours
logout()
}
// value previously stored
}
} catch(e) {
// error reading value
}
}

希望能有所帮助。无需怀疑

最新更新