是否有可能知道RN应用程序是否已进入后台?有回电或触发器吗?
如果我在屏幕上听componentDidUnmount
或componentWillUnmount
次,只有在我来回切换到另一个屏幕时,它才会被触发
是否有可能知道RN应用程序是否已进入后台?有回电或触发器吗?
如果我在屏幕上听componentDidUnmount
或componentWillUnmount
次,只有在我来回切换到另一个屏幕时,它才会被触发
你可以收听appState
事件.
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>
);
}
}
顺便说一句,它总是说"当前状态为:活动",因为这是应用程序对用户可见的唯一状态.