简体   繁体   English

在redux动作中使用socketio

[英]Using socketio in redux actions

I'm trying to build an application using React, Redux and socket.io ! 我正在尝试使用React,Redux和socket.io构建应用程序! My question is : how do you initialize event listeners (which are actions in Redux) like this one : 我的问题是:如何初始化事件监听器(这是Redux中的操作),如下所示:

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

in React without having access to the componentWillMount since I'm using functional programing on components. 在React中没有访问componentWillMount,因为我在组件上使用了函数编程。

My current problem is that if I pass the method 我目前的问题是,如果我通过该方法

addNotif addNotif

to my component, every time a new notification comes in, the store is updated, and so the component is re-rendered and therefore it adds another socket.on event and this keeps on going. 对于我的组件,每次有新的通知进入时,商店都会更新,因此组件会被重新渲染,因此它会添加另一个socket.on事件,并且这种情况会持续进行。

Any ideas on how to fix that in a clean way ? 关于如何以干净的方式解决这个问题的任何想法? Thanks ! 谢谢 !

Try to define and export the function like this: 尝试定义和导出这样的函数:

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

As you mention, you don't want to attach an event listener inside a stateless function. 如您所述,您不希望在无状态函数中附加事件侦听器。 You wanna invert this: notification comes in > dispatch event . 你想反过来: notification comes in > dispatch event This can live outside the lifecycle of react since you can dispatch arbitrary redux actions from anywhere. 这可以存在于反应的生命周期之外,因为您可以从任何地方发送任意的redux动作。

If the action is not consumed because there are no clients that's fine. 如果没有使用该操作,因为没有客户端没问题。 You can fine tune this by absorbing/demuxing events in a redux middleware and/or have components dispatch subscriptions. 您可以通过吸收/解压缩redux中间件中的事件和/或使用组件调度订阅来对此进行微调。

index.js index.js

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

notifications.js 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');
    })
  },
};

It might be a good idea to abstract away the socketio interface, hence the two files although it's not necessary. 抽象出socketio接口可能是一个好主意,因此这两个文件虽然没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM