Reactjs:如何在组件之间共享 websocket [英] Reactjs: how to share a websocket between components

查看:58
本文介绍了Reactjs:如何在组件之间共享 websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 的新手,我在组件结构和在它们之间共享 websocket 方面遇到了一些问题.

I'm new to React and I'm having some issues regarding components structure and sharing a websocket between them.

该应用由类别和产品组成.初始数据加载将通过 Ajax 请求完成,并将使用 websocket 保持数据更新.

The app consists of categories and products. The initial data load will be done with an Ajax request and a websocket will be used keep data updated.

我的组件层次结构如下所示:

My component hierarchy looks like this:

  • 类别列表
    • 类别
      • 产品列表
        • 产品

        CategoriesList 保存类别的状态,ProductsList 保存类别内产品的状态.

        CategoriesList holds the state of categories and ProductsList holds the state of products within a category.

        所以我想在 CategoriesList 和 ProductsList 中使用相同的 websocket,但监听不同的 websocket 事件:category:updated 和 product:updated.

        So I would like to use the same websocket inside CategoriesList and ProductsList but listening to different websocket events: category:updated and product:updated.

        如何在组件之间共享 websocket 以及初始化它的正确位置?

        How do I share the websocket between components and where is the right place to initialize it?

        由于每个类别都有一个 ProductsList,这是否意味着 products:updated 事件将触发多次(每个类别一个)?我想这在性能方面不是一件好事.

        Since there is one ProductsList for each Category, does this means that the products:updated event will fire multiple times ( one for each category )? I guess this isn't a good thing in terms of performance.

        推荐答案

        我建议在 CategoriesList 中初始化您的套接字连接,然后将连接作为道具传递给子组件.当连接向下传递时,您应该能够使用它来根据需要在子组件中侦听特定事件.

        I recommend initializing your socket connection in CategoriesList and then passing down the connection as props to the child components. When the connection is passed down, you should be able to use it to listen for specific events as needed in the child components.

        这是 github 上使用 react 和 socket.io 的示例应用程序.套接字在父组件中初始化,然后向下传递.https://github.com/raineroviir/react-redux-socketio-chat/blob/master/src/common/containers/ChatContainer.js

        Here's an example application on github that uses react and socket.io. The socket is initialized in a parent component and then passed down. https://github.com/raineroviir/react-redux-socketio-chat/blob/master/src/common/containers/ChatContainer.js

        在第 9 行初始化连接,然后在第 23 行它作为 props 传递.该连接稍后在子组件中用于接收和发出事件.例如:https://github.com/raineroviir/react-redux-socketio-chat/blob/master/src/common/components/Chat.js

        On line 9 the connection is initialized and then on line 23 it's passed down as props. The connection is later used in child components to receive and emit events. Ex: https://github.com/raineroviir/react-redux-socketio-chat/blob/master/src/common/components/Chat.js

        这篇关于Reactjs:如何在组件之间共享 websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆