在redux动作中使用socketio

时间:2018-02-28 15:28:37

标签: javascript reactjs socket.io redux

我正在尝试使用React,Redux和socket.io构建应用程序! 我的问题是:如何初始化事件监听器(这是Redux中的操作),如下所示:

export const addNotif = () => (dispatch) => {
  socket.on('notification', (message) => {
    dispatch(notification(message))
  })
}

在React中无法访问componentWillMount,因为我在组件上使用了函数编程。

我目前的问题是如果我传递方法

  

addNotif

到我的组件,每次有新的通知进入时,商店都会更新,因此组件会被重新渲染,因此它会添加另一个socket.on事件,并且这种情况一直在继续。

关于如何以干净的方式解决这个问题的任何想法? 谢谢!

2 个答案:

答案 0 :(得分:3)

尝试定义和导出这样的函数:

export const addNotif = (dispatch) => {
  socket.on('notification', (message) => {
    dispatch(notification(message))
  })
}

答案 1 :(得分:2)

如您所述,您不希望在无状态函数中附加事件侦听器。 你想要反驳这个:notification comes in > dispatch event。这可以存在于反应的生命周期之外,因为你可以从任何地方发送任意的redux动作。

如果没有使用该操作,因为没有客户端没问题。您可以通过吸收/解压缩redux中间件中的事件和/或让组件调度订阅来对此进行微调。

<强> index.js

// start() should be called ONCE wherever you have access to the store 
const notifications = require('./notifications');
notifications.start(store.dispatch);

<强> notifications.js

export default {
  start(dispatch) {
    socker.on('connect', () => {
      console.log('Subscribed to notifications');
    });
    socket.on('notification', (payload) => {
      dispatch(({ type: "NOTIF", payload }));
    });
    socket.on('error', (message) => {
      console.log('TODO: handle error');
    })
  },
};

抽象出socketio接口可能是一个好主意,因此这两个文件虽然不是必需的。