我正在app.js中为createStackNavigator导入chatscreen.js。我在chatscreen.js中有var socket = socketio.getSocket();
代码,当导入代码在app.js中运行时,此getSocket();运行。
我想运行socketio.socketConnect();在app.js中导入chatscreen.js之前,但我无法创建此逻辑
App.js
import ChatScreen from './components/ChatScreen/ChatScreen';
import socketio from './components/Classes/socketio';
import SplashScreen from './components/SplashScreen/SplashScreen';
class App extends Component{
constructor(props){
super(props);
}
}
const RootStack = createStackNavigator(
{
Splash:{screen: SplashScreen},
Chat:{screen: ChatScreen},
}
ChatScreen.js
import socketio from '../Classes/socketio';
var socket = socketio.getSocket();
class ChatScreen extends Component{
constructor(props){
super(props);
}
}
socketio.js
import React, { Component } from 'react';
import io from "socket.io-client";
let socket;
class socketio extends Component{
static socketConnect(domain){
socket = io("http://"+domainToken,{jsonp:false})
}
static getSocket(){
if (!socket) {
throw new Error("Must call socketConnect() before getSocket()");
}
return socket;
}
}
export default socketio;
答案 0 :(得分:0)
问题出在您的socketio.js上,您使它成为一个类组件,而应该使它成为这样的功能组件:
import io from "socket.io-client";
let socket;
function socketConnect(domain){
socket = io("http://"+domainToken,{jsonp:false})
}
function getSocket(){
if (!socket) {
throw new Error("Must call socketConnect() before getSocket()");
}
return socket;
}
module.exports = {
socketConnect,
getSocket
}
然后您可以像这样导入它:
import socketio from '../Classes/socketio';
var socket = socketio.getSocket();
class ChatScreen extends Component{
constructor(props){
super(props);
}
componentDidMount(){
socketio.socketConnect(domain)
}
}