无限循环反应和socket.io
Endless loop in react and socket.io
我正在尝试构建实时聊天消息。在客户端(React),每当有新用户进入聊天时,套接字的事件 usuarios-conectados 就会被触发(这个套接字事件给了我当时连接的所有用户的数组).
然后,我尝试在 useState 中设置该用户数组,但正因为如此,组件进入循环并不断重新呈现自身。
这似乎是问题所在,因为每当我调用 useSocket 时,console.log(users) 都会不断打印已连接的用户一遍又一遍
import { useEffect, useState } from 'react'
import { io } from "socket.io-client";
export const useSockets = () => {
const [socket, setSocket] = useState(
io('http://localhost:8080', {
'extraHeaders': {
'x-token': localStorage.getItem('x-token')
}
})
)
const [users, setUsers] = useState([])
useEffect(() => {
socket.on('connect', () => {
console.log('Sockets online')
})
socket.on('usuarios-conectados', (newUsers) => {
setUsers(newUsers);
console.log(users);
})
return () => {
socket.on('disconnect', () => {
console.log('Sockets offline')
})
socket.disconnect()
}
}, [])
return [users]
}
您不应该将 io 存储在状态中,而是创建一个文件并导入到您的组件中,然后在您初始化套接字之后,它本身将监听您定义的事件。让我在代码中展示。
//src/utils/socket.js
import io from "socket.io-client"
export const socket = io(process.env.BACKURL);
// component.jsx
import {socket} from './utils/socket'
const [commentData , setCommentData] = useState([]);
useEffect(() => {
socket.on("connect_error", () => {
console.error("socket error!");
socket.close();
});
// websokcet to comments
socket.on("load_comment", (payload) => {
setCommentData(payload);
});
return () => {
socket.close();
}
}, [])
// second useEffect to see if statesChanged
useEffect(() => {
console.log('Changed' , commentData)
} , [commentData])
您不应该将 IO 存储在状态中,而是在上下文中调用它,例如,让我在代码中显示。
- 创建上下文
import React from 'react';
import io from 'socket.io-client';
const SOCKET_ADDR = process.env.REACT_APP_SOCKET_ADDR || '<your server>';
export const socket = io(SOCKET_ADDR, { withCredentials: false, transports: ['websocket'] });
export const SocketContext = React.createContext();
- 然后添加到任何你想要的地方
import { SocketContext, socket } from './socket/SocketContext';
useEffect(() => {
socket.on('connect', () => {
socket.on('welcome', (res) => {
console.log(res);
});
});
});
我正在尝试构建实时聊天消息。在客户端(React),每当有新用户进入聊天时,套接字的事件 usuarios-conectados 就会被触发(这个套接字事件给了我当时连接的所有用户的数组).
然后,我尝试在 useState 中设置该用户数组,但正因为如此,组件进入循环并不断重新呈现自身。
这似乎是问题所在,因为每当我调用 useSocket 时,console.log(users) 都会不断打印已连接的用户一遍又一遍
import { useEffect, useState } from 'react' import { io } from "socket.io-client"; export const useSockets = () => { const [socket, setSocket] = useState( io('http://localhost:8080', { 'extraHeaders': { 'x-token': localStorage.getItem('x-token') } }) ) const [users, setUsers] = useState([]) useEffect(() => { socket.on('connect', () => { console.log('Sockets online') }) socket.on('usuarios-conectados', (newUsers) => { setUsers(newUsers); console.log(users); }) return () => { socket.on('disconnect', () => { console.log('Sockets offline') }) socket.disconnect() } }, []) return [users] }
您不应该将 io 存储在状态中,而是创建一个文件并导入到您的组件中,然后在您初始化套接字之后,它本身将监听您定义的事件。让我在代码中展示。
//src/utils/socket.js
import io from "socket.io-client"
export const socket = io(process.env.BACKURL);
// component.jsx
import {socket} from './utils/socket'
const [commentData , setCommentData] = useState([]);
useEffect(() => {
socket.on("connect_error", () => {
console.error("socket error!");
socket.close();
});
// websokcet to comments
socket.on("load_comment", (payload) => {
setCommentData(payload);
});
return () => {
socket.close();
}
}, [])
// second useEffect to see if statesChanged
useEffect(() => {
console.log('Changed' , commentData)
} , [commentData])
您不应该将 IO 存储在状态中,而是在上下文中调用它,例如,让我在代码中显示。
- 创建上下文
import React from 'react';
import io from 'socket.io-client';
const SOCKET_ADDR = process.env.REACT_APP_SOCKET_ADDR || '<your server>';
export const socket = io(SOCKET_ADDR, { withCredentials: false, transports: ['websocket'] });
export const SocketContext = React.createContext();
- 然后添加到任何你想要的地方
import { SocketContext, socket } from './socket/SocketContext';
useEffect(() => {
socket.on('connect', () => {
socket.on('welcome', (res) => {
console.log(res);
});
});
});