在react-redux中存储套接字连接的位置?

时间:2017-02-19 16:58:20

标签: reactjs react-redux phoenix-framework phoenix-channels

尝试了两种方式:

  1. connectToServer()的{​​{1}}组件中的操作创建者致电Starter,并按照以下方式发送:

    componentDidMount();
  2. 接下来,我通过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是空的。

    1. 将所有逻辑放入reducer中,但结果是:使用空道具(未定义属性)呈现组件,并在我在控制台日志中看到建立连接但是组件已经呈现之后。
    2. 如何处理这样的问题?感谢您的任何建议。

1 个答案:

答案 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。