避免使插座.io连接两次
我正在frontend上使用React,并在后端表示
我编写了以下代码以将客户端连接到后端,
import React, { useEffect,useState} from 'react'
import { io } from "socket.io-client"
const Video = () => {
const [socket,setSocket] = useState(io("http://localhost:3001"));
const myVideo = document.createElement('video')
myVideo.muted = true;
useEffect(() => {
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
addVideoStream(myVideo, stream)
})
}, [])
但是插座连接事件为单个网页打开了两次。 请告诉我问题在哪里,我添加或删除的内容仅在每个用户中建立一个连接。
I am using react at frontend and express on backend
I wrote the following code to connect client to backend
import React, { useEffect,useState} from 'react'
import { io } from "socket.io-client"
const Video = () => {
const [socket,setSocket] = useState(io("http://localhost:3001"));
const myVideo = document.createElement('video')
myVideo.muted = true;
useEffect(() => {
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
addVideoStream(myVideo, stream)
})
}, [])
But the socket onconnection event fired twice for a single webpage opening.
Please tell me where is the problem, what i add or remove to make only one connection per user .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一个useref进行调试以查看严格模式是否是问题:
在这里,您会看到计数保持在1,因此使用效果中的函数仅触发一次
try a useRef for debugging to see if strict mode is the problem:
here you will see that the count stays at 1, so the functin in useEffect is only fired once
很快这是一个想法...这可能有点虚假,因为我没有尝试过,但是这里的想法是将您呼叫io呼叫,并实现条件,以免调用您的呼叫两次。您可能可以通过加载程序条件来改进它,如果呼叫未成功等,该加载程序条件不会返回您的套接字。
Pretty quickly here is an idea... it might be a bit falsy because i haven't tried it out, but the idea here is to extract you io call into a custom hook, and implement a condition so that your call is not called twice. You can probably improve this with a loader condition that does not return your socket if the call hasn't been successfull etc..