是否有可能知道RN应用程序是否已进入后台?有回电或触发器吗?

如果我在屏幕上听componentDidUnmountcomponentWillUnmount次,只有在我来回切换到另一个屏幕时,它才会被触发

推荐答案

你可以收听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>
    );
  }

}

顺便说一句,它总是说"当前状态为:活动",因为这是应用程序对用户可见的唯一状态.

React-native相关问答推荐

1.5.1 nxworkspace+react-native 版本的Axios url未定义问题

expo 日历应用因权限问题而崩溃

React Native:无法将具有 resizeMode包含的图像定位在父组件的 flex-end

react-native 根据状态隐藏显示按钮

Invariant Violation:requireNativeComponent: "RNCWebView" was not found in the UIManager

如何在react-native 中处理不同的屏幕尺寸?

使用 Hooks 在功能组件中react-navigation 标题

React Native - 如何判断 UI/元素?

如何在 React Native cli 中获取 SHA-1 密钥?

NativeBase + Exponent Header

FlatList contentContainerStyle -> justifyContent: 'center' 导致滚动问题

错误:无法解析模块`buffer`

如果我有 AngularJS 基础知识,怎么学习Thinking in ReactJS呢?

如何在 react-native 中从 AsyncStorage 中删除元素

React Nativedropped so far性能监视器计数不断增加

React Native 中使用了哪些维度单位?

如何将捕获的图像与 react-native-camera 一起使用

如何在 Text 中围绕 Text 包裹 TouchableOpacity?

react-native Bottom Up drawer

如何将props传递给 React Navigation 导航器中的组件?