离开并重新加入Socket.io房间后出现多个消息

时间:2019-06-01 17:46:10

标签: node.js reactjs

我让用户在安装React组件时加入一个房间,然后在卸载时离开房间。离开然后重新加入房间后,用户会收到两条消息。然后在以下尝试中执行3,依此类推。我在整个交易中都使用相同的套接字。 (或者至少认为我是)

我尝试不同时加入两个房间,也没有在用户连接处留下连接,并且仍然出现相同的问题。

// Server side - App.js
// Required Express, http server, and socket.io
require('./middleware/socket')(io);

// socket.js
module.exports = io => {
    io.on('connection', socket => {
        socket.on('join', data => {
            socket.join(data.room);
        });
        socket.on('leave', data => {
            socket.leave(data.room);
        });

        socket.on('event', data => {
            socket.in('event').emit('event', {username: data.username, msg: data.msg});
        });
        socket.on('package', data => {
            socket.in('package').emit('package', {username: data.username, msg: data.msg});
        });
    });
}
// Client Side index.js
import io from 'socket.io-client';
const socket = io('http://localhost:8080');
// Pass Socket to Child Component - event.js
<Switch>
...
<Route exact path="/event">
  <Event 
    endpoint={this.state.endpoint}
    username={name}
    _event={this.state.package}
    socket={socket}
/>
</Route>
</Switch>
// event.js
componentDidMount = () => {
        this.props.socket.emit('join', {room: 'event'});
        this.props.socket.on('event', data => {
            document.querySelector('.posts').innerHTML += `${data.username} said: ${data.msg}<br/>`;
        });
    }
componentWillUnmount = () => {
        this.props.socket.emit('leave', {room: 'event'});
    }

我希望用户离开房间,当他们重新加入时,只会收到一条消息。

1 个答案:

答案 0 :(得分:0)

componentDidMount中,您每次都会添加event侦听器,而不会在componentWillUnmount中将其删除

eventListener = (data) => {
    document.querySelector('.posts').innerHTML += `${data.username} said: ${data.msg}<br/>`;
}

componentDidMount = () => {
    ...
    this.props.socket.on('event', this.eventListener);
    document.querySelector('.posts').innerHTML = ''
}

componentWillUnmount = () => {
    ...
    this.props.socket.off('event', this.eventListener);
}