我是React Native的新手,并且有一个奇怪的问题。
我有两个组件Visitor
和Visitor Chat Details
。在Visitor
中连接到WebSocket,并将Websocket Prop发送给Visitor Chat Details
。
我在Visitor
和Visitor Chat Details
上都会收听消息。在Visitor
组件中,侦听消息且效果很好。但是,当我将组件更改为Visitor Chat Details
时,它会在Visitor
组件上禁用onmessage
事件。Visitor Chat Details
中的唯一工作事件。
这是访客组件
export class VisitorListScreen extends React.Component {
constructor(props) {
super(props);
this.state = { isConnected: false, ws: null, fullname: '', username: '', alias: '', userId: null, hash: '', status: true, users: [] }
...
this.connect = this.connect.bind(this);
this.connectClient = this.connectClient.bind(this);
}
componentDidMount() {
...
this.connect();
}
connect() {
const SERVER_ID = createServerId();
const CONNECTION_ID = createConnectionId();
var ws = new WebSocket('wss://myurl.com/im/websocket');
this.setState({ ws: ws });
ws.onopen = () => {
// connection opened
console.log("connected")
this.setState({ isConnected: true });
};
ws.onmessage = e => {
console.log("listening");
// a message was received
this.handleMessage(e.data);
};
ws.onerror = e => {
// an error occurred
console.log("An error occured");
};
ws.onclose = e => {
// connection closed
console.log("connection closed");
this.setState({ isConnected: false });
TimerMixin.setTimeout(() => {
if (!this.state.isConnected) {
console.log("Reconnecting...");
this.connect();
}
}, 5000);
}
}
handleMessage(data) {
...
}
connectClient(user) {
this.props.navigation.navigate('VisitorDetail', { user: user, agentFullname: this.state.fullname, agentId: this.state.userId, ws: this.state.ws });
}
...
和访客聊天详细信息组件
export class VisitorDetail extends React.Component {
constructor(props) {
super(props);
const params = this.props.navigation.state.params;
let isServing = params.user.servingAgent != null && params.user.servingAgent == params.agentFullname;
this.state = { isServing:isServing, agentFullname: '', username: '', alias: '', agentId: '', hash: '', typing: '', user: params.user, ws: params.ws, messages: [] };
this.sendMessage = this.sendMessage.bind(this);
this.loadMessages = this.loadMessages.bind(this);
this.registerRoom = this.registerRoom.bind(this);
this.handleMessage = this.handleMessage.bind(this);
this.startChat = this.startChat.bind(this);
this.state.ws.onmessage = e => {
console.log("visitor detail listening");
console.log(e.data);
//this.handleMessage(e.data);
}
}
componentWillMount() {
..
}
componentDidMount() {
this.loadMessages();
this.registerRoom();
}
loadMessages() {
const siteId = 'cc76df43-da21-4b62-81be-4868b11c43dc';
...
}
registerRoom() {
...
}
startChat (){
您首先在访问者组件中创建一个WebSocket实例" WS",并设置
ws.onmessage = e => // 1st function
然后,在访问者聊天详细信息中,您将获得相同的WebSocket" WS",然后将onmessage
重置为另一个功能:
this.state.ws.onmessage = e => // 2nd function
您刚刚更改了onmessage
,第二个功能将被调用,而不是第一个功能。