【问题标题】:React native appstate using to check user online and offlineReact native appstate 用于检查用户在线和离线
【发布时间】:2021-03-19 19:38:56
【问题描述】:

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

提前致谢。

【问题讨论】:

    标签: react-native


    【解决方案1】:

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

    【讨论】:

    • 感谢您的时间。谢谢。
    • 不客气。如果您的问题已得到解答,请不要忘记将其标记为答案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多