首页 > 解决方案 > React native appstate 用于检查用户在线和离线

问题描述

我是 React Native 的新手,我正在开发 React Native 上的消息应用程序。如果 appState 是 Active/inActive 并且确切地在哪个页面(在根/索引处)或在 HomePage 登录后,我如何实现更改用户在线/离线状态的功能,它将是全局的吗?在应用程序的所有页面中使用?

提前致谢。

标签: react-native

解决方案


React Native 本身提供 AppState,如果应用程序当前处于后台或只是处于活动状态,您可以轻松地在 App.js 中检查。如果应用程序处于活动状态,那么您可以调用后端函数将在线状态设置为 true。由于您在根文件 (App.js) 中执行此操作,因此侦听器适用于所有文件。

import React, { useRef, useState, useEffect } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";

const AppStateExample = () => {
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);

  useEffect(() => {
    AppState.addEventListener("change", _handleAppStateChange);

    return () => {
      AppState.removeEventListener("change", _handleAppStateChange);
    };
  }, []);

  const _handleAppStateChange = (nextAppState) => {
    if (
      appState.current.match(/inactive|background/) &&
      nextAppState === "active"
    ) {
      // TODO SET USERS ONLINE STATUS TO TRUE
    } else {
     // TODO SET USERS ONLINE STATUS TO FALSE
    }

    appState.current = nextAppState;
    setAppStateVisible(appState.current);
    console.log("AppState", appState.current);
  };

  return (
    <View style={styles.container}>
      <Text>Current state is: {appStateVisible}</Text>
    </View>
  );
};

推荐阅读