【发布时间】:2023-03-30 02:47:01
【问题描述】:
我已经设置了 React + Redux 并添加了 socket.io。在 UI 输入框中,当我输入内容时,我可以将其传递给操作,然后是套接字,然后向访问该页面的所有浏览器发出信号。
我知道io.on('action', data => console.log(data)) 是每个浏览器接收socket广播的信号的方式。但是如果我想使用这个信号来更新每个浏览器的状态,我应该把它放在 action 文件还是 redux 文件中?
申请代码:
io.on('action', data => console.log(data)) //will write something to update the state
动作文件提取:
export const handleNameInput = (name) => {
return {
type: InviteeActionTypes.ADD_HANDLENAMEINPUT,
meta: {remote: true},
name
};
}
redux 文件提取:
case InviteeActionTypes.ADD_HANDLENAMEINPUT: {
return {
...state,
pendingGuest : action.name
};
}
服务器文件代码:
var http = require('http');
var server = http.createServer();
var socket_io = require('socket.io');
server.listen(4000);
var io = socket_io();
io.attach(server);
io.on('connection', function(socket){
console.log("Socket connected: " + socket.id);
socket.on('action', (action) => {
if(action.type === 'invitee/ADD_HANDLENAMEINPUT'){
console.log('Data : ', action.name);
io.local.emit('action', {type:'message', data:action.name});
}
});
});
【问题讨论】:
标签: reactjs socket.io redux react-redux