【问题标题】:WebSocket onmessage connection is null React-ReduxSagaWebSocket onmessage 连接为空 React-ReduxSaga
【发布时间】:2020-09-03 21:57:33
【问题描述】:

我得到一个空的.onmessage 但是 .onopen 正在工作

import * as types from './types';
import { eventChannel } from 'redux-saga';
import { takeEvery, put, call, select, take } from 'redux-saga/effects';


export function* createEventChannel() {
  const mySocket = new WebSocket('wss://url.com');
  return eventChannel((emit: any) => {
    mySocket.onopen = () => {
      mySocket.send("sdsdsdsd!");
    };
// =====> onmessage is getting null
    mySocket.onmessage((message:any) => {
        emit(message.data)
    });

    return () => {
      mySocket.close();
    };
    
  });
}

export function* workWebSocket(action:any) {
  const channel = yield call(createEventChannel);
  while (true) {
    const { message } = yield take(channel);
    yield put({ type: types.WEB_SOCKET_SUCCESS, message: message });
  }
}

export default function* watchHydration() {
  yield takeEvery(types.WEB_SOCKET_FETCH, workWebSocket);
}

关于我为什么会为空的任何建议?

【问题讨论】:

    标签: reactjs redux websocket redux-saga


    【解决方案1】:

    看看这个例子:你能正确解析数据吗?

    function initWebsocket() {
    return eventChannel(emitter => {
    ws = new WebSocket(wsUrl + '/client')
    ws.onopen = () => {
      console.log('opening...')
      ws.send('hello server')
    }
    ws.onerror = (error) => {
      console.log('WebSocket error ' + error)
      console.dir(error)
    }
    ws.onmessage = (e) => {
      let msg = null
      try {
        msg = JSON.parse(e.data)
      } catch(e) {
        console.error(`Error parsing : ${e.data}`)
      }
      if (msg) {
        const { payload: book } = msg
        const channel = msg.channel
        switch (channel) {
          case 'ADD_BOOK':
            return emitter({ type: ADD_BOOK, book })
          case 'REMOVE_BOOK':
            return emitter({ type: REMOVE_BOOK, book })
          default:
            // nothing to do
        }
      }
    }
    // unsubscribe function
    return () => {
      console.log('Socket off')
     }
    })
    }
    export default function* wsSagas() {
    const channel = yield call(initWebsocket)
     while (true) {
      const action = yield take(channel)
      yield put(action)
    }
     }
    

    【讨论】:

    • 是的,我确实正确解析了数据。但我发现我在箭头函数 onMessage // =====> This is where I made a mistake mySocket.onmessage = function ((message:any) => { emit(message.data) }); 上犯了一个错误
    • 我很高兴这对您有所帮助。我也发现了mySocket.onmessage
    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2021-11-05
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多