具有socket.io状态的UseEffect挂钩在套接字处理程序中不持久

Moh*_*ajr 6 socket.io webrtc reactjs react-hooks

我有以下反应成分

function ConferencingRoom() {
    const [participants, setParticipants] = useState({})
    console.log('Participants -> ', participants)

    useEffect(() => {
        // messages handlers
        socket.on('message', message => {
            console.log('Message received: ' + message.event)
            switch (message.event) {
                case 'newParticipantArrived':
                    receiveVideo(message.userid, message.username)
                    break
                case 'existingParticipants':
                    onExistingParticipants(
                        message.userid,
                        message.existingUsers
                    )
                    break
                case 'receiveVideoAnswer':
                    onReceiveVideoAnswer(message.senderid, message.sdpAnswer)
                    break
                case 'candidate':
                    addIceCandidate(message.userid, message.candidate)
                    break
                default:
                    break
            }
        })
        return () => {}
    }, [participants])

    // Socket Connetction handlers functions

    const onExistingParticipants = (userid, existingUsers) => {
        console.log('onExistingParticipants Called!!!!!')

        //Add local User
        const user = {
            id: userid,
            username: userName,
            published: true,
            rtcPeer: null
        }

        setParticipants(prevParticpants => ({
            ...prevParticpants,
            [user.id]: user
        }))

        existingUsers.forEach(function(element) {
            receiveVideo(element.id, element.name)
        })
    }

    const onReceiveVideoAnswer = (senderid, sdpAnswer) => {
        console.log('participants in Receive answer -> ', participants)
        console.log('***************')

        // participants[senderid].rtcPeer.processAnswer(sdpAnswer)
    }

    const addIceCandidate = (userid, candidate) => {
        console.log('participants in Receive canditate -> ', participants)
        console.log('***************')
        // participants[userid].rtcPeer.addIceCandidate(candidate)
    }

    const receiveVideo = (userid, username) => {
        console.log('Received Video Called!!!!')
        //Add remote User
        const user = {
            id: userid,
            username: username,
            published: false,
            rtcPeer: null
        }

        setParticipants(prevParticpants => ({
            ...prevParticpants,
            [user.id]: user
        }))
    }

    //Callback for setting rtcPeer after creating it in child component
    const setRtcPeerForUser = (userid, rtcPeer) => {
        setParticipants(prevParticpants => ({
            ...prevParticpants,
            [userid]: { ...prevParticpants[userid], rtcPeer: rtcPeer }
        }))
    }

    return (
            <div id="meetingRoom">
                {Object.values(participants).map(participant => (
                    <Participant
                        key={participant.id}
                        participant={participant}
                        roomName={roomName}
                        setRtcPeerForUser={setRtcPeerForUser}
                        sendMessage={sendMessage}
                    />
                ))}
            </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

它具有的唯一状态是使用useState挂钩定义调用的参与者哈希表。

然后我使用useEffect来监听聊天室的套接字事件,只有4个事件

然后在那之后,我针对服务器上的执行顺序为这些事件定义4个回调处理程序

最后,我还有另一个回调函数,该函数传递给列表中的每个子参与者,以便在子组件创建其rtcPeer对象后,将其发送给父对象,以将其设置在参与者的hashTable中的参与者对象上

流程类似于此参与者进入会议室-> 调用了existingParticipants事件->创建了本地参与者并将其添加到参与者hashTable中,然后-> recieveVideoAnswer和服务器多次发出了候选人,如屏幕快照所示。

状态的第一个事件为空,随后的两个事件为空,然后再次为空,此模式不断重复一个空状态,然后以下两个是正确的,我不知道状态是怎么回事

在此处输入图片说明

Rya*_*ell 42

关于这一点的困难在于,您在相互交互时遇到了几个问题,这些问题使您的故障排除感到困惑。

最大的问题是您正在设置多个套接字事件处理程序。每次重新渲染,您都在调用socket.on而从未调用过socket.off.

我可以想象出三种主要的方法来处理这个问题:

  • 建立一个单一的插座事件处理程序,只使用功能更新participants状态。使用这种方法,您将使用一个空的依赖数组useEffect,并且您不会在您的效果中引用participants 任何地方(包括您的消息处理程序调用的所有方法)。如果您确实引用participants了第一次重新渲染,您将引用它的旧版本。如果participants使用功能更新可以轻松完成需要发生的更改,那么这可能是最简单的方法。

  • 设置一个新的套接字事件处理程序,每次更改participants. 为了使其正常工作,您需要删除之前的事件处理程序,否则您将拥有与渲染相同数量的事件处理程序。当您有多个事件处理程序时,创建的第一个事件处理程序将始终使用participants(empty)的第一个版本,第二个将始终使用 的第二个版本participants等。这将起作用,并为您如何使用现有participants状态,但具有反复拆卸和设置套接字事件处理程序的缺点,这感觉很笨重。

  • 设置单个套接字事件处理程序并使用 ref 访问当前participants状态。这与第一种方法类似,但增加了在每次渲染时执行的附加效果,以将当前participants状态设置为 ref,以便消息处理程序可以可靠地访问它。

无论您使用哪种方法,我认为如果您将消息处理程序从渲染函数中移出并显式传入其依赖项,您将更容易推理代码正在做什么。

第三个选项提供与第二个选项相同的灵活性,同时避免重复设置套接字事件处理程序,但在管理participantsRef.

这是使用第三个选项的代码的样子(我没有尝试执行它,所以我不保证我没有轻微的语法问题):

const messageHandler = (message, participants, setParticipants) => {
  console.log('Message received: ' + message.event);

  const onExistingParticipants = (userid, existingUsers) => {
    console.log('onExistingParticipants Called!!!!!');

    //Add local User
    const user = {
      id: userid,
      username: userName,
      published: true,
      rtcPeer: null
    };

    setParticipants({
      ...participants,
      [user.id]: user
    });

    existingUsers.forEach(function (element) {
      receiveVideo(element.id, element.name)
    })
  };

  const onReceiveVideoAnswer = (senderid, sdpAnswer) => {
    console.log('participants in Receive answer -> ', participants);
    console.log('***************')

    // participants[senderid].rtcPeer.processAnswer(sdpAnswer)
  };

  const addIceCandidate = (userid, candidate) => {
    console.log('participants in Receive canditate -> ', participants);
    console.log('***************');
    // participants[userid].rtcPeer.addIceCandidate(candidate)
  };

  const receiveVideo = (userid, username) => {
    console.log('Received Video Called!!!!');
    //Add remote User
    const user = {
      id: userid,
      username: username,
      published: false,
      rtcPeer: null
    };

    setParticipants({
      ...participants,
      [user.id]: user
    });
  };

  //Callback for setting rtcPeer after creating it in child component
  const setRtcPeerForUser = (userid, rtcPeer) => {
    setParticipants({
      ...participants,
      [userid]: {...participants[userid], rtcPeer: rtcPeer}
    });
  };

  switch (message.event) {
    case 'newParticipantArrived':
      receiveVideo(message.userid, message.username);
      break;
    case 'existingParticipants':
      onExistingParticipants(
          message.userid,
          message.existingUsers
      );
      break;
    case 'receiveVideoAnswer':
      onReceiveVideoAnswer(message.senderid, message.sdpAnswer);
      break;
    case 'candidate':
      addIceCandidate(message.userid, message.candidate);
      break;
    default:
      break;
  }
};

function ConferencingRoom() {
  const [participants, setParticipants] = React.useState({});
  console.log('Participants -> ', participants);
    const participantsRef = React.useRef(participants);
    React.useEffect(() => {
        // This effect executes on every render (no dependency array specified).
        // Any change to the "participants" state will trigger a re-render
        // which will then cause this effect to capture the current "participants"
        // value in "participantsRef.current".
        participantsRef.current = participants;
    });

  React.useEffect(() => {
    // This effect only executes on the initial render so that we aren't setting
    // up the socket repeatedly. This means it can't reliably refer to "participants"
    // because once "setParticipants" is called this would be looking at a stale
    // "participants" reference (it would forever see the initial value of the
    // "participants" state since it isn't in the dependency array).
    // "participantsRef", on the other hand, will be stable across re-renders and 
    // "participantsRef.current" successfully provides the up-to-date value of 
    // "participants" (due to the other effect updating the ref).
    const handler = (message) => {messageHandler(message, participantsRef.current, setParticipants)};
    socket.on('message', handler);
    return () => {
      socket.off('message', handler);
    }
  }, []);

  return (
      <div id="meetingRoom">
        {Object.values(participants).map(participant => (
            <Participant
                key={participant.id}
                participant={participant}
                roomName={roomName}
                setRtcPeerForUser={setRtcPeerForUser}
                sendMessage={sendMessage}
            />
        ))}
      </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

此外,下面是一个模拟上面代码中发生的事情的工作示例,但没有使用socket以清楚地显示使用participantsparticipantsRef. 观察控制台并单击两个按钮以查看传递participants给消息处理程序的两种方式之间的区别。

import React from "react";

const messageHandler = (participantsFromRef, staleParticipants) => {
  console.log(
    "participantsFromRef",
    participantsFromRef,
    "staleParticipants",
    staleParticipants
  );
};

export default function ConferencingRoom() {
  const [participants, setParticipants] = React.useState(1);
  const participantsRef = React.useRef(participants);
  const handlerRef = React.useRef();
  React.useEffect(() => {
    participantsRef.current = participants;
  });

  React.useEffect(() => {
    handlerRef.current = message => {
      // eslint will complain about "participants" since it isn't in the
      // dependency array.
      messageHandler(participantsRef.current, participants);
    };
  }, []);

  return (
    <div id="meetingRoom">
      Participants: {participants}
      <br />
      <button onClick={() => setParticipants(prev => prev + 1)}>
        Change Participants
      </button>
      <button onClick={() => handlerRef.current()}>Send message</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑可执行示例

  • 难道还没有更好的办法吗?不断地打开和关闭连接是相当疯狂的 (4认同)
  • @Jessica我意识到你的评论是很久以前的事了,但是如果你仍在寻找另一种选择,我已经用我在有效果的情况下使用的第三种方法(使用参考)更新了这个答案由于我想要执行效果的时间,我不希望在依赖项数组中存在依赖项。 (3认同)
  • @Ryan 这是一个关于如何使用钩子解决现实世界问题的精彩示例。非常感谢! (2认同)