【问题标题】:How to use the same socket on different pages in react nativereact-native 如何在不同页面上使用相同的套接字
【发布时间】:2022-01-22 02:06:50
【问题描述】:

我在我的 react-native 项目中使用 Socket.io 来提供聊天功能。我的项目正在使用反应原生导航。 但是我在将 Socket.io 套接字传递到某些屏幕时遇到了麻烦。我想与导航共享套接字(就像我认为我不确定的道具)。 目前,我在每个特定屏幕上单独使用 Socket.io 套接字。但是这种方式有一些麻烦。 主要的问题是,当有人给我发消息时,我需要知道应用程序运行时我在哪个页面上。 有人对如何做有任何建议吗? 我的目标是与三个页面共享同一个套接字。 我用谷歌搜索,但找不到任何合适的结果。

- AppNavigation.js

import React from 'react';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';


// Chat.
import ChatScreen from '../screens/Chat/ChatScreen';
import VideoChatScreen from '../screens/Chat/VideoChatScreen;


const Stack = createStackNavigator();

function AppNavigator() {

  return (
    <NavigationContainer>
      <Stack.Navigator>
            <Stack.Screen name="Chat" component={ChatScreen} options={{ headerShown: false, gestureEnabled: false }}/>
            <Stack.Screen name="VideoChat" component={VideoChatScreen} options={{ headerShown: false, gestureEnabled: false }}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default AppNavigator;


- ChatScreen.js

import React, { Component } from 'react';
import {connect} from 'react-redux';
import SocketIOClient from 'socket.io-client'

class ChatScreen extends Component {
  constructor() {
    super()
    this.state = {}
    this.socketClient = null;
  }

  componentDidMount() {
    this.socketClient = SocketIOClient(url);
    this.socketClient.onAny((event, params) => {
      this.onResponseOnSocket(event, params);
    });
  }

  ...


 - VideoChatScreen.js

 import React, { Component } from 'react';
 import {connect} from 'react-redux';

class VideoChatScreen extends Component {
  constructor() {
    super()
    this.state = {}
    this.socketClient = null;
  }

  componentDidMount() {
    this.socketClient = SocketIOClient(url);
    this.socketClient.onAny((event, params) => {
      this.onResponseOnSocket(event, params);
    });
  }

 ...

【问题讨论】:

    标签: react-native socket.io chat


    【解决方案1】:

    我认为我的图书馆非常适合您的情况。 是专用于聊天应用的状态管理工具:https://github.com/chatscope/use-chat

    您的应用程序应该使用 ChatProvider 组件进行包装,并且您需要创建自己的服务/适配器来负责 websocket 连接。

    发送消息、消息列表、对话等在所有子组件中都可用一个钩子。

    【讨论】:

      【解决方案2】:

      您可以使用您选择的状态管理工具来管理应用内的全局 (App-)State。对于功能组件,我喜欢 ContextProvider,它是 RN Core 的一部分,并且仍然可以。对于类组件,只要您只有几个 Provider。但是很多人使用 Redux,或者你可以使用 facebooks Recoil,这也是一个有趣的选择。

      https://reactjs.org/docs/context.html

      https://redux.js.org/introduction/getting-started

      https://recoiljs.org/

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 1970-01-01
        • 2019-07-13
        • 1970-01-01
        • 2013-03-15
        • 2014-11-09
        • 2020-09-19
        • 2016-07-20
        • 2012-01-02
        相关资源
        最近更新 更多