Redux Socket.io Middleware多次调度一个动作

时间:2018-04-20 12:09:56

标签: reactjs react-native redux socket.io react-redux

我有以下格式的自定义redux操作,该操作应该侦听socket.io服务器发出的一组事件,并根据触发的事件调度带有效负载的操作。问题是当从服务器发出一次事件时,中间件似乎在某些情况下发射超过4或5次导致应用程序崩溃。可能是什么问题。 中间件的代码如下:

import io from "socket.io-client";
import { WORKOUT_EVENTS } from "./constants";

export default socketIOReduxMiddleware = store => next => action => {
    const socket  = io("http://192.168.1.16:3001", { reconnect: true, pingTimeout: 10000, pingInterval: 3000, transports: ["websocket", "polling"] });

    WORKOUT_EVENTS.forEach(event => {
        socket.on(event, payload => {
            store.dispatch({ type: event, payload });
        }); 
    });
    next(action);
};

常量文件包含以下代码:

export const WORKOUT_EVENTS = [
"start workout",
"wait trigger",
"phase countdown",
"phase break",
"exercise countdown",
"exercise",
"exercise explanation",
"round countdown",
"main phase exercises",
"station change",
"end workouts"
];

这是完整的中间件代码。

1 个答案:

答案 0 :(得分:0)

在设置时发现store => next => {}块被调用一次,但每次调度操作时都会调用action => {}块。然后工作代码变为

import io from 'socket.io-client';

import WORKOUT_EVENTS from './constants';

const socketIOReduxMiddleware = store => next => {
    const socket = io("192.168.1.8:8089", {  pingInterval: 3000, pingTimeout: 10000,transports: ["websocket", "polling"]
      });

    WORKOUT_EVENTS.forEach(event => {
        socket.on(event, payload => {
            store.dispatch({ type: event, payload});
        });
    });

    return action => {
        next(action);
    }
}

export default socketIOReduxMiddleware;