仅在满足条件时初始化套接字连接

时间:2018-09-11 05:43:08

标签: reactjs redux sockjs

我试图在我的react / redux Web应用程序中创建套接字连接,并且仅在用户登录时尝试初始化套接字连接。我的套接字实例当前位于中间件中,但是当我尝试检查是否记录了一个用户,我收到类似Uncaught TypeError: Cannot read property 'apply' of undefined的错误。这是中间件代码的片段:

const socketMiddleWare = url => store => {
  if (store.getState().user.username) {
    const socket = new SockJS(url, [], {
      sessionId: () => custom_token_id
    });
    socket.onopen = e => {
      console.log("Connection", e.type);

      if (e.type === "open") {
        store.dispatch({ type: types.TOGGLE_SOCK_OPENED });
        createSession(custom_token_id, store);
      }
    };

    socket.onclose = () => {
      console.log("Connection closed");
    };

    socket.onmessage = e => {
      const message = JSON.parse(e.data);
    };

    return next => action => {
      if (
        action.type === types.SEND_SOCKET_MESSAGE
      ) {
        socket.send(JSON.stringify(action.payload));
        return;
      } else if (action.type === types.USER_LOGGED_OUT) {
        socket.close();
      }
      next(action);
    };
  }
};
`

`
const middleWare = applyMiddleware(
     routerMiddleware(history),
     sagaMiddleware,
     promise(),
     thunk,
     socketMiddleWare(`${config("LOCALHOST").url}`)
  );
`

`
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const store = createStore(
  rootReducer,
  persistedState,
  composeEnhancers(middleWare)
);

谢谢。

0 个答案:

没有答案