在 React 中放置 websocket 的位置 [英] Where to put your websocket in React

查看:53
本文介绍了在 React 中放置 websocket 的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 socket.io 和 react,但我仍然不知道从哪里启动 socket = io(endpoint).在我看过的大多数教程中,他们似乎将它放在组件级别(低于应用程序级别.我假设每当您切换路由和组件卸载时它都会断开连接).但是,如果您想始终如一地收听某些事件,而不管您在应用程序中导航到哪条路线,该怎么办?这就是我的意思:

I have been trying to use socket.io with react for some time and I still don't know where to initiate socket = io(endpoint). In most tutorials I have seen, they seem to put it at the component level (below the app level. I assume it disconnects whenever you switch routes and the component unmounts). But what if you want to listen to some events consistently regardless of which route you navigate to in your app? Here is what I mean:

let socket 

const App = () => {
  useEffect(() => {
    socket = io(endpoint)
    socket.on('Application wide event', callback)
  }, []) 
}

然后你通过 props 传递套接字吗?我已经尝试过这种方法,有时子组件甚至在成功创建 App 套接字之前就想在安装时立即发出一个事件,从而引发错误.也许像这样?:

Do you then pass the socket via props? I have tried this approach and sometimes the child componenets wants to emit an event immediately on mount even before the App socket can be successfully created and thus throws an error. Perhaps something like this? :

/* socket initialization here */
const App = () => {}

传统做法是什么?

推荐答案

我遇到了与您类似的问题,无论您在我的应用中导航到哪条路线,我都需要始终如一地监听某些事件.我设法通过在渲染函数之外初始化顶层组件上的套接字并导出它来完成它,因此当我需要发出或侦听套接字时,我只需导入它.

I encountered a problem like yours that I need to listen to some events consistently regardless of which route you navigate to in my app. I manage to do it by initialized the socket on the top level component outside rendering function and exported it, so when I need to emit or listen to a socket I will just import it.

/* socket initialization here */
socket = io(endpoint);

const App = () => {
    //return <Routes>...</Routes>
}

export default App;
export {socket};

这将导致套接字初始化一次,以便需要它的组件可以立即触发或侦听它.

This will lead to socket initialized once so the component that needs it can fire an emit or listen to it immediately.

并使用它:

import {socket} from "/App";

const OtherComponent = () => {
    useEffect(() => {
        socket.on("Application wide event", callback)
        return () => {
            socket.off("Application wide event");
        }
    }, [])
}

我仍然想知道这是否是一种传统做法,但它对我有用,我会关注这个问题,也许有人知道更好的传统做法.

I still wondering if this is a conventional practice but it works on me, I will follow this question, maybe someone knows a better conventional practice.

这篇关于在 React 中放置 websocket 的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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