如何将socket.io客户端与reactjs集成?

时间:2019-01-01 18:42:53

标签: reactjs debugging socket.io

在我的reactjs中,ComponentDidMount()订阅“聊天”消息,并且当套接字接收到新消息时,它们将被推送到组件状态。当用户输入消息并提交表单时,该消息将作为JSON发送到后端

two muppets

这是我的socket.io后端

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

app.use(function(req, res, next) {
 res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Headers", "Origin, X-Requested- 
 With, Content-Type, Accept");
 next();
});

server.listen(3000)

io.on('connection', function(socket) {
  console.log('user connected');

socket.on('disconnect', function() {
 console.log('user disonnected');
})

socket.on('chat', function(data) {
 io.emit('chat',data);
})
})

这是我的反应组件:

    state = {
     currentRoom: {
        messages: [],
        message: ""
    }
};

componentDidMount() {
    socket.on('chat', message => {
        message.key = JSON.stringify(message);
        this.setState((prevState) => {
            let messages=prevState.currentRoom.messages;
            messages.push(message) {
                messages:messages
            }
        })
    })

}

0 个答案:

没有答案