在 React Native 中检查用户是否在线

时间:2021-04-14 09:02:30

标签: firebase react-native google-cloud-firestore

我有社交应用,我想检查用户是在线还是离线:

我了解 React Native 中的 Appstate,并且我有一页 Web JS HTML 用于管理它(社交应用)

所以我的问题是如何在 myAPP 中看到在线用户,而在 myWeb 中看到这个?

我有这样的解决方法:

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

只要我在线 => 我就会将状态添加到 Firestore 1 数据中

db.collection("data").doc("userA").set(
....
status:'online'
).then(() => {
    console.log("change status is sussecd");
});

然后在我的网站

 db.collectionGroup('User').where('status', '==','online').onSnapshot(user => {
          someQuery.....//
        })

还有什么办法吗?

1 个答案:

答案 0 :(得分:0)

问题不在于用户在线的写作,因为他们会在发生这种情况时处于活动状态。问题是当他们失去连接时将他们标记为离线。

Firestore 对此没有很好的内置支持,因为它的协议是无连接的。但是有一个将其与实时数据库相结合的解决方案,并记录在此处:https://firebase.google.com/docs/firestore/solutions/presence

您也可以直接在您的应用中使用实时数据库,manage presence无需 Cloud Functions 或 Firestore。

相关问题