【发布时间】: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