在React Native中应用程序处于后台状态时清除间隔



我想知道如何在我的应用程序进入后台状态时清除间隔。

有时,当我单击"主页"按钮时,我的应用程序将被关闭(willUnmount事件不会触发(,然后间隔永远不会被清除。

你怎么知道如果应用程序关闭,间隔永远不会被清除?(只是好奇(如果应用程序被关闭,它应该根本不工作,不是吗?只有当你有后台定时器也许会运行?

但我认为如果你关闭应用程序,它应该停止吗?我认为在您的情况下,您可以使用来自react native的AppState来检测应用程序是否返回前台,然后重置间隔?

import React, {
Component
} from "react";
import {
AppState,
StyleSheet,
Text,
View
} from "react-native";
export default class AppStateExample extends Component {
state = {
appState: AppState.currentState
};
componentDidMount() {
AppState.addEventListener("change", this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener("change", this._handleAppStateChange);
}
_handleAppStateChange = nextAppState => {
if (
this.state.appState.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!"); //reset interval here
}
this.setState({
appState: nextAppState
});
};
render() {
return ( 
<View style = {
styles.container
} >
<Text>
Current state is: {
this.state.appState
}</Text> 
</View >
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});

最新更新