【问题标题】:Using socketio in redux actions在 redux 操作中使用 socketio
【发布时间】:2018-02-28 15:28:36
【问题描述】:

我正在尝试使用 React、Redux 和 socket.io 构建一个应用程序! 我的问题是:您如何像这样初始化事件侦听器(Redux 中的操作):

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

在 React 中没有访问 componentWillMount 因为我在组件上使用函数式编程。

我目前的问题是,如果我通过方法

添加通知

对于我的组件,每次收到新通知时,商店都会更新,因此组件会重新渲染,因此它会添加另一个 socket.on 事件,并且会继续进行。

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

【问题讨论】:

  • 这是一个在redux handlermedium.com/@gethylgeorge/…中使用sockets的小程序的例子,也许会有点帮助
  • @SterlingArcher 遗憾的是它没有!他在 Redux 中唯一使用 socket.on 的地方,之后他没有调用该操作(代码中已注释:()

标签: javascript reactjs socket.io redux


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    正如您所提到的,您不想在无状态函数中附加事件侦听器。 你想反转这个:notification comes in > dispatch event。这可以存在于 react 的生命周期之外,因为您可以从任何地方调度任意 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接口可能是个好主意,因此这两个文件虽然不是必需的。

    【讨论】:

    • 嗯,我有点喜欢这种方法,但是我可以在容器中初始化函数 addNotif 并且不将其作为道具提供给孩子,这是一种不好的做法吗?
    • 我认为在 redux 操作中附加事件侦听器有点令人困惑。目前尚不清楚它是否会再次分派,这会导致事件侦听器泄漏。
    猜你喜欢
    • 2017-12-09
    • 2021-10-04
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多