简体   繁体   English

React Native socket.io 无法收听“socket.on”侦听器

[英]React Native socket.io not able to listen to "socket.on" listener

I am trying to build a chat app and to produce realtime effect, I'm using socket.io , I developed my server in node/express and it's working perfect, but the problem is in react-native side, as I'm not able to render the messages when the socket.on is used (even though I'm doing it in correct way, I entered the correct dependency in the useEffect ).我正在尝试构建一个聊天应用程序并产生实时效果,我正在使用socket.io ,我在 node/express 中开发了我的服务器,它运行良好,但问题出在 react-native 方面,因为我无法渲染使用socket.on时的消息(即使我以正确的方式进行操作,我在useEffect中输入了正确的依赖项)。 Below is some of the code from my app, and I will confirm that some parts are working fine, something is wrong only just in the useEffect dependencies list.以下是我的应用程序中的一些代码,我将确认某些部分工作正常,仅在useEffect依赖项列表中出现问题。

Server side logic to listen/send message to target client ids:用于侦听/发送消息到目标客户端 ID 的服务器端逻辑:

socket.on('sendMessage', ({senderId, receiverId, text}) => {
        console.log(text); // getting the output as expected here.
        const user = Utility.getUser(users, receiverId);
        io.to(user.socketId).emit('getMessage', {
            senderId,
            text,
        });
    });

Client side / React Native side:客户端/React Native 端:

const socket = useRef();
    const [arrivalMessage, setArrivalMessage] = useState(null);

    useEffect(() => {
        // connect to server/api link
        socket.current = io('...', {
            transports: ['websocket'],
        });
    }, []);

    useEffect(() => {
        socket.current.on('getMessage', data => {
            console.log('getmessages: ',data);
            setArrivalMessage({
                // matchId: matchId,
                senderId: data.senderId,
                text: data.text,
                createdAt: Date.now(),
                updatedAt: Date.now(),
            });
        });
    // SOMETHING IS WRONG HERE, as this useEffect block is not being executed even though I have mentioned "socket" in my dependency list.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [socket]);

    useEffect(() => {
        // ensures we don't get any other user's msg
        arrivalMessage &&
        match.includes(arrivalMessage.senderId) &&
        setMessages((prev) => [...prev, arrivalMessage]);
    }, [arrivalMessage, match]);

So, something is wrong in the 2nd useEffect as this useEffect block is not being executed even though I have mentioned "socket" in my dependency list, and hence the chatlist is not updated.所以,第二个useEffect问题,因为即使我在依赖项列表中提到了“socket”,这个 useEffect 块也没有被执行,因此聊天列表没有更新。 Also, there are no error logs in console so it adds more difficulty to debug...此外,控制台中没有错误日志,因此增加了调试难度......

I would really appreciate if someone point out what I'm doing wrong!如果有人指出我做错了什么,我将不胜感激!

You cannot use useRef for the socket instance... mutating reference doesn't re-render content of the component therefore it doesn't trigger the useEffect您不能将useRef用于套接字实例...变异引用不会重新呈现组件的内容,因此它不会触发useEffect

Here is an example how to use sockets in hook这是一个如何在钩子中使用 sockets 的示例

export function useSocket(
  url = process.env.NEXT_PUBLIC_API_URL /* default URL */
) {
  const [socket, setSocket] = useState<SocketType>(null)

  useEffect(() => {
    const io: SocketType = SocketClient(url).connect()
    setSocket(io)

    return () => {
      socket?.disconnect()
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return socket
}

export function useSocketEvent(
  socket: SocketType,
  event: keyof SocketListenEventMap,
  callback: (...args: unknown[]) => void
) {
  useEffect(() => {
    if (!socket) {
      return
    }

    socket.on(event, callback)

    return () => {
      socket.off(event, callback)
    }
  }, [callback, event, socket])

  return socket
}

export function useMessagesSocket() {
  const [arrivalMessage, setArrivalMessage] = useState(null)
  const socket = useSocket(/* URL */)

  useSocketEvent(socket, 'getMessages', (data) =>
    setArrivalMessage({
      //...
    })
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM