【发布时间】:2018-03-21 13:57:08
【问题描述】:
是否有可能知道 RN 应用程序是否已进入后台?任何回调或触发器?
如果我收听当前屏幕的componentDidUnmount 或componentWillUnmount,则只有在我返回/返回另一个屏幕时才会触发
【问题讨论】:
是否有可能知道 RN 应用程序是否已进入后台?任何回调或触发器?
如果我收听当前屏幕的componentDidUnmount 或componentWillUnmount,则只有在我返回/返回另一个屏幕时才会触发
【问题讨论】:
您可以收听appState 事件。
来自https://facebook.github.io/react-native/docs/appstate.html:
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>
);
}
}
顺便说一句,这将始终显示“当前状态为:活动”,因为这是应用对用户可见的唯一状态。
【讨论】:
react-native-orientation 切换回横向。
您可以使用AppState:
应用状态
active- 应用正在前台运行background- 应用程序正在后台运行。用户在另一个应用中或在主屏幕上inactive- 这是在前台和后台之间转换时以及在不活动期间(例如进入多任务视图或来电时)发生的状态
【讨论】:
AppState.removeEventListener 似乎已被弃用,所以我这样做了:
import React from 'react'
import { AppState } from 'react-native'
class AppStateClassComponent extends React.PureComponent {
constructor(props){
super(props)
this.state = {
appState: ''
}
this.onAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({ appState: nextAppState });
}
this.app_state = null
}
componentDidMount() {
this.permission_check()
if(this.app_state === null){
this.app_state = AppState.addEventListener('change', this.onAppStateChange)
}
}
componentWillUnmount() {
if(this.app_state !== null){
this.app_state?.remove()
this.app_state = null
}
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
)
}
}
【讨论】: