我正在将React-player用于基于观看方的Web应用程序,用户可以在其中创建房间,并在房间中创建其他用户。 添加后,任何用户都可以执行操作,该操作将应用于会议室中的所有其他用户。在这种情况下,我正在使用django-channels进行websocket处理。 如果存在由用户触发的暂停事件,则将websocket事件发布给所有用户,并基于该事件为所有其他用户暂停视频。 现在的问题来了,当视频在传入事件中暂停时,又会导致onPause操作和发送事件。 为了解决这个问题,我使用了useState挂钩来确定我们是否要发送事件。
但是在我的情况下,当视频因传入事件而暂停时,onPaouse会发生两次。
const [playing, setPlaying] = useState(false);
const [userName, setUserName] = useState(getUserName());
const [sendEvent, setSendEvent] = useState("true");
const player = useRef(null);
const [videoUrl, setVideoUrl] = useState(DEFAULT_VIDEO_URL)
useEffect(() => {
const websocketUrl = `ws://127.0.0.1:8000/room/`;
socket = new W3CWebSocket(websocketUrl);
socket.onmessage = (message) => {
const data = JSON.parse(message.data)
if (data.event === 'pause') {
console.log(`I am ${userName}`);
console.log(data);
if (userName !== data.name) { // do not perform for the user who invoked it
console.log(`inside if by ${userName}`);
player.current.seekTo(data.currentTime);
setSendEvent(false); // do not send event
setPlaying(false); //pause the video
}
}
}
}, [])
const playerPause = () => {
console.log(`trying to pause by ${userName} with sendEvent: ${sendEvent}`);
if (sendEvent === true) { //skip sending events
socket.send(JSON.stringify({
'name': userName,
'event': 'pause',
'currentTime': player.current.getCurrentTime()
}));
}
setSendEvent(true); // so that new events can be sent again
}
<ReactPlayer ref={player} url={videoUrl} controls={true} playing={playing} onPause={playerPause} />
SAMPLE ERROR IN GIF
如您所见,第二个用户获得了两个事件。第一次运行正常,因为sendEvent为False,但是由于某种原因,它再次调用playerPause()
函数,这导致了问题,并且事件再次被发送。
您能帮我在这里找到潜在的问题吗?