問題描述
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 .