将socket.io与redux reducer结合

时间:2020-01-31 12:49:31

标签: react-native redux socket.io

堆栈-React native,socket.io,Node.js

我正在开发聊天应用程序。在这一点上,我有这样的流程: 用户单击“发送消息”->该消息由socket.io发送到服务器->服务器上的套接字连接获取该消息。 现在,从那一点开始,我想要的是将消息从服​​务器发送到redux还原器,然后该还原器将返回前端组件将呈现的新状态。
如何在服务器端套接字和reducer之间建立连接?

当前服务器:

    const express = require("express");
    const app = express();
    const port = 3000;
    const server = require("http").createServer(app);
    let io = require("socket.io")(server);

    app.get("/", (req, res) => res.send("Hello World!"));

    io.on("connection", socket => {
      console.log("a user connected");

      socket.on("join", (name, message) => {
      console.log("chat room connected")
      });

    });

    server.listen(port, () => console.log(`listening on port ${port}!`));

减速器:

    const initialState = {
      chats: [

      ]
    };
    const chatsReducer = (state = initialState, action) => {
      let sender = action.sender;
      let message = action.message;

      switch (action.type) {
        case SEND_MESSAGE:
          let newMessage = {
            sender: sender,
            message: message
          };

          let newState = { ...state, chats: state.chats.push(newMessage) };
          return state;

        default:
          state;
      }
      return state;
    };

    export default chatsReducer;

1 个答案:

答案 0 :(得分:1)

您可以像这样从节点服务器发出新消息。

OPTION (RECOMPILE)

然后在您的聊天组件中侦听聊天消息事件。

let msg = {message: 'Actual Message', sender: 'Name of sender'}
io.on('connection', socket => {
  socket.on('chat message', msg => {
    io.emit('chat message', msg);
  });
}); 

然后添加操作:

 componentDidMount() {
    this.socket = io("http://server.address:port");
    this.socket.on("chat message", msg => {
       this.props.onMessageReceivedAction (msg); // import action and will execute on message received event
   });
});

将收到的减速器箱消息添加到减速器中

export const onMessageReceivedAction = (params) => {
  return  {type: MESSAGE_RECEIVED, payload:msg};
};

这将返回新状态,并且映射到上述状态的组件props将被重新渲染。

希望这会回答您的问题。