next.js socket.io 使用效果不更新套接字消息 (next.js socket.io useeffect not updating on socket message)


問題描述

next.js socket.io 使用效果不更新套接字消息 (next.js socket.io useeffect not updating on socket message)

我在 next.js 上遇到了我的套接字客戶端的問題。我已經創建了一個上下文,用於為應用程序中的所有組件提供我的套接字實例,問題是當我想在我的組件上使用套接字上下文時,我正在使用 useeffect 鉤子,一旦套接字被更改,我將處理消息調用(就像我在網上看到的任何教程一樣)但是在套接字上有新消息時,根本不會調用 useEffect 。對於那些可能認為這是上下文問題的人,我應該說它不是我已經在組件本身上測試了套接字啟動並且仍然沒有調用 useeffect。
這是我使用套接字實例的方式:

export default function MyComp(props){
    const cookies = new Cookies()
    const token = cookies.get('token');
    const socket = io(routes.socket_url, { path: '/socket',
        transports: ['websocket'],
        query:{
        token,
        user_id:'someuserid'
    } 
    });

   useEffect(() => {
        console.log('socket changed');
        console.log(socket);
        console.log('socket changed');
   },[socket])
}


參考解法

方法 1:

guys i found the answer . i was using socket.io‑client v 3.1.1 and i started testing other versions . for some strange reason
in version 3 socket instance is not receiving any messages though the connection is already stablished and i can see the messages coming in the networks tab .
anyways i changed version from 3 to 2.1.1 and its working like a charm .

(by faramarzfaramarz)

參考文件

  1. next.js socket.io useeffect not updating on socket message (CC BY‑SA 2.5/3.0/4.0)

#react-context #react-hooks #sockets #Socket.io #Next.js






相關問題

在項目中使用 Context API 我以前會在異步操作創建者中使用 Redux? (Using Context API in a project I would have previously used Redux in - async action creators?)

Nextjs 和上下文 API (Nextjs and Context API)

從 redux-saga 函數訪問 React 上下文值 (Access React context value from redux-saga function)

如何在 Django 應用程序中用 react ContextAPI 替換 Redux (How can you replace Redux by the react ContextAPI in a Django App)

從深度嵌套的組件更新狀態而不重新渲染父組件 (Update state from deeply nested component without re-rendering parents)

更新 useContext 中的值時,組件不會重新呈現 (Component not re rendering when value from useContext is updated)

為什麼我無法從反應上下文訪問變量?你能找出錯誤嗎? (Why am I not able to access variable from react context? Can you identify the mistake?)

React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))

React Context 是道具鑽探的解毒劑嗎? (Is React Context an antidote for prop drilling?)

主題提供者問題 (Theme Provider issue)

打字稿反應上下文+類型'{}'沒有調用簽名 (Typescript react context + Type '{}' has no call signatures)

next.js socket.io 使用效果不更新套接字消息 (next.js socket.io useeffect not updating on socket message)







留言討論