react-native - React native appstate 用于检查用户在线和离线
问题描述
我是 React Native 的新手,我正在开发 React Native 上的消息应用程序。如果 appState 是 Active/inActive 并且确切地在哪个页面(在根/索引处)或在 HomePage 登录后,我如何实现更改用户在线/离线状态的功能,它将是全局的吗?在应用程序的所有页面中使用?
提前致谢。
解决方案
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>
);
};
推荐阅读
- sql-server - SQL Server 在查询中注销/终止登录用户的会话
- java - java程序错误中的方法重载
- hibernate - 使用 SpringBoot 懒惰初始化角色集合失败
- gradle - 使用 Kotlin DSL 进行集成测试的独立 Gradle 源集
- windows - Docker 容器中的 Selenium 和 Windows 集成身份验证
- windows - 有没有办法使用 python 或批处理文件更改 Windows 7 主题
- php - Google API 中的令牌格式无效
- python - PyCharm 运行 python 脚本时的操作是什么?
- java - 将 GWT 2.5 Web 应用程序迁移到 Java 10
- webpack - css-loader,导出 css 模块映射