【问题标题】:Redux & Socket IO proxy errorRedux & Socket IO 代理错误
【发布时间】:2018-07-30 04:58:24
【问题描述】:

我正在使用以下插件在 Redux 中管理我的 Socket IO 实例:

https://github.com/itaylor/redux-socket.io

我只需要在我的用户登录后才能初始化套接字。插件在文档中建议在设置商店时设置套接字实例:

import { createStore, applyMiddleware } from 'redux';
import createSocketIoMiddleware from 'redux-socket.io';
import io from 'socket.io-client';

let socket = io('http://localhost:3000');
let socketIoMiddleware = createSocketIoMiddleware(socket, "server/");

function reducer(state = {}, action){
  switch(action.type){
    case 'message':
      return Object.assign({}, {message:action.data});
    default:
      return state;
  }
}

let store = applyMiddleware(socketIoMiddleware)(createStore)(reducer);

store.subscribe(()=>{
  console.log('new client state', store.getState());
});
store.dispatch({type:'server/hello', data:'Hello!'});

由于我无法在设置商店的同时设置实例,我需要找到一种稍后设置它的方法。我在 redux-socket.io 问题中找到了这个解决方案:

https://github.com/itaylor/redux-socket.io/issues/13#issuecomment-256095866

似乎是一个完美的解决方案,所以我用我当前的商店设置实现了它:

import {applyMiddleware,createStore} from 'redux';
import rootReducer from './reducers/___index';
import thunk from 'redux-thunk';

let socketIoMiddleware = null;
const proxyMiddleware = store => next => action => {
  if (socketIoMiddleWare !== null) {
     return socketIoMiddleware(store)(next)(action);
  }
  return next(action);
}

const middlewares = [proxyMiddleware, thunk];
const store = createStore(rootReducer,applyMiddleware(...middlewares));

商店呈现良好,没有错误,但是当我尝试通过单击按钮更改商店状态中的任何内容时,我收到以下错误:

socketIoMiddleWare 未定义

我在 redux-socket.io 存储库中找到的上述解决方案似乎对其他人有效,所以我不完全确定为什么会出现此错误。

任何建议将不胜感激!

【问题讨论】:

    标签: javascript reactjs sockets redux


    【解决方案1】:

    这里的if(socketIoMiddleWare !== null) { 应该是socketIoMiddleware。好像是错别字

    【讨论】:

    • 有时候真的是这样。但这实际上很好。因为您确实输入了它并且没有复制和粘贴。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2014-09-14
    • 2014-01-17
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多