尝试了两种方式:
从connectToServer()
的{{1}}组件中的操作创建者致电Starter
,并按照以下方式发送:
componentDidMount();
接下来,我通过redux的mapStateToProps let socket = new Socket('ws://address/socket');
socket.connect();
dispatch({
type: Constants.SESSION_SAVE_SOCKET,
socket: socket,
});
const lobbyChannel = socket.channel('lobby');
lobbyChannel.join()
.receive('ok', () => {
dispatch({
type: Constants.SESSION_LOBBYCHANNEL_RECEIVE_OK,
});
dispatch({
type: Constants.SESSION_SAVE_LOBBYCHANNEL,
lobbyChannel: lobbyChannel,
});
}).receive('error', (payload) => {
dispatch({
type: Constants.SESSION_LOBBYCHANNEL_RECEIVE_ERROR,
});
});
接收状态。
结果是组件被调用四次,结果中的props是空的。
如何处理这样的问题?感谢您的任何建议。
答案 0 :(得分:3)
我发现这样做的方法是为套接字设置自己的中间件,如此。
import {createStore, applyMiddleware} from 'redux';
import startWs, {wsMiddleware} from './ws.api';
function handleData(state = {data1: {}}, action) {
switch (action.type) {
case 'ApiGotData': return Object.assign({}, state, {data1: action.data});
default: return state;
}
}
const store = createStore(handleData, applyMiddleware(wsMiddleware));
startWs(store);
export default store;
import * as Actions from './Actions';
var socket = null;
const newData = {
'React version': '15',
'Project': 'Redux with socket.io',
'currentDateTime': new Date().toLocaleString()
};
export function wsMiddleware() {
return (next) => (action) => {
if (socket && action.type === 'ApiGetData') {
console.log('ApiGetData');
socket.emit('client:GetData', {});
} else if (socket && action.type === 'ApiSetData') {
console.log('ApiSetData');
socket.emit('client:SetData', action.data);
}
return next(action);
};
}
export default function (store) {
socket = new io();
socket.on('server:GetDataDone', (data) => {
console.log('GetDataDone');
store.dispatch(Actions.apiGotData(data));
});
socket.on('server:SetDataDone', () => {
console.log('SetDataDone');
store.dispatch(Actions.apiGetData());
});
store.dispatch(Actions.apiSetData(newData));
}
项目示例是https://github.com/jmarkstevens/ReactPatterns的ReduxSocketIO。