将插座连接存储在React-Redux中



尝试了两种方法:

  1. componentDidMount();中的Starter组件中调用connectToServer(),并以此为单位:

    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,
        });
    });
    

接下来,我通过Redux的MapStateToprops connect接收状态。结果是组件称为四次,结果在结果时为空。

  1. 将所有逻辑放入还原器中,但结果是:组件用空的道具(未定义的属性)渲染,并且在我在控制台日志中看到连接已建立的时刻,但是已经呈现了组件。

如何处理这样的问题?感谢您的建议。

我发现有效的方式是为套接字设置自己的中间件。

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/reaectpatterns的ReduxSocketio。

相关内容

  • 没有找到相关文章

最新更新