簡體   English   中英

在 React 上使用 sockets 時如何防止重新渲染?

[英]How to prevent re-render when using sockets on React?

我的代碼有這個問題,它喜歡多次重新渲染並重新連接到服務器,我想要它,以便在他們登錄時連接,這意味着它必須使用我的“useAuth ()" function 使用不同的上下文。

有什么辦法可以防止重新渲染,所以它不會重新連接多次而只連接一次?

這是我的代碼:

import React, { useEffect } from "react";
import { useAuth } from "./AuthContext";
import { io } from "socket.io-client";

const SocketContext = React.createContext({});

export const SocketProvider = ({ children }) => {
   const { isAuthenticated, user } = useAuth();
   useEffect(() => {
      if (isAuthenticated) {
         const socket = io("ws://localhost:3002", {
            reconnectionDelayMax: 10000,
            auth: {
               token: user.socketAuth,
            },
         });

         socket.on("connect_error", (err) => {
            if (err instanceof Error) {
               console.log(err.message);
               console.log(err.data);
            }
         });
      }
   }, []);
   return <SocketContext.Provider value="">{children}</SocketContext.Provider>;
};

沒關系,我解決了這個問題,它按照它應該的方式工作。 是服務器不接受連接,它只是不斷記錄套接字的 ID 而實際上並沒有讓它連接。

io.use(async (socket, next) => {
   const user = await User.findOne({ socketAuth: socket.handshake.auth.token });
   if (!user) {
      const err = new Error("Unauthorized");
      err.data = { message: "Unauthorized, please try again later." };
      next(err);
   }
   next(); // New line added to allow connection
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM