如何在React Native中监听App的启动和关闭?

问题描述 投票:0回答:2

我需要在应用程序启动和关闭时跟踪一些日志事件(仅一次)。

首先我在

Home
屏幕
componentDiMount()
中执行此操作,但在某些情况下它会被实例化多次,导致重复启动事件日志。

================编辑================

AppState
只能监听backgroundactive事件。

在Android上关闭应用程序时(按返回键或在最近使用的应用程序菜单中关闭),它实际上返回到背景。重新打开应用程序时,它会将应用程序从 background 返回到 active。这与在backgroundactive(不关闭)

之间切换应用程序相同

所以我无法确定它是首次启动还是使用AppState

切换应用程序状态

android ios react-native
2个回答
3
投票

应用程序启动时

一般来说,带有空依赖项数组的

useEffect
就是您要寻找的。

在 React Native 中,当应用程序状态不活动时,代码可以运行,但是具有空依赖项数组的

useEffect
将在第一次应用程序启动时运行。

如果您使用依赖项值,则可以使用

useRef
来跟踪它是否在首次应用启动时处理。

const onLaunchRef = React.useRef<boolean>();

useEffect(() => {
  if (onLaunchRef.current) {
    return;
  }
  doSomething(state1, state2);
  onLaunchRef.current = true;
}, [state1, state2]);

您可以将其与 useAppState 结合使用:

import { useAppState } from '@react-native-community/hooks'

const onLaunchRef = React.useRef<boolean>();
const appState = useAppState();

useEffect(() => {
  if (onLaunchRef.current) {
    return;
  }
  if (appState !== 'active') {
    return;
  }
  doSomething(state1, state2);
  onLaunchRef.current = true;
}, [state1, state2, appState]);

在应用程序关闭时

您可以使用以下内容:

useEffect(() => {
  return () => {
    doSomething(state1, state2);
  };
}, [state1, state2]);

或使用

useAppState
:

const appState = useAppState();
useEffect(() => {
  if (appState !== 'active') {
    doSomething();
  }
}, [appState]);

然而,React Native 中并不存在实际的关闭事件。这是一个有点棘手的问题。


1
投票

注意:以下答案是在 OP 未编辑问题以添加有关 AppState 限制的信息时编写的。

自 2021 年 2 月 16 日编辑起生效。

使用

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>
    );
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.