【发布时间】:2018-10-05 19:35:52
【问题描述】:
如何检测从后台到前台 es6 的任何方法?
这在 React-native 中可行吗?是否有任何类或工具可以帮助这种类型的方法?
【问题讨论】:
标签: android react-native-android onresume onpause
如何检测从后台到前台 es6 的任何方法?
这在 React-native 中可行吗?是否有任何类或工具可以帮助这种类型的方法?
【问题讨论】:
标签: android react-native-android onresume onpause
试试这个,它对我有用
import React, {Component} from 'react'
import {AppState, Text} from 'react-native'
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!')
}
this.setState({appState: nextAppState});
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
);
}
}
【讨论】:
作为对现有答案的更新,removeEventListener(type, handler) 已成为 deprecated(自 2021 年 9 月起):
对返回的事件订阅使用 remove() 方法 addEventListener()
import React, {Component} from 'react'
import {AppState, Text} from 'react-native'
class AppStateExample extends Component {
state = {
appState: AppState.currentState
}
eventListenerSubscription = null;
componentDidMount() {
this.eventListenerSubscription = AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
this.eventListenerSubscription.remove();
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({appState: nextAppState});
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
);
}
}
import React, { useState, useEffect } from 'react';
import { AppState, Text } from 'react-native';
function AppStateExample() {
const [appState, setAppState] = useState(AppState.currentState);
var eventListenerSubscription;
const _handleAppStateChange = nextAppState => {
if (appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!');
}
setAppState(nextAppState);
};
useEffect(() => {
//on mount
eventListenerSubscription = AppState.addEventListener('change', _handleAppStateChange);
return () => {
// on unmount
eventListenerSubscription.remove();
};
}, []);
return <Text>Current state is: {appState}</Text>;
}
export default AppStateExample;
【讨论】: