重复渲染
- 0
#讨论区
00条评论
实时对话
loading...
tsx
tsx
'use client';
import { io, Socket } from 'socket.io-client';
import { useEffect, useRef, useState } from 'react';
import Monitor from 'utils/monitor';
const OnlineCount = () => {
const [count, setCount] = useState(0);
const socket = useRef<WebSocket>();
async function initSocket() {
const monitor = new Monitor();
const userId = await monitor.getVisitor();
socket.current = new WebSocket(`ws://localhost:3000/v1/ws?userId=$userId`)
socket.current.onmessage = (event)=>{
const message = event.data;
setCount(message)
}
}
useEffect(() => {
initSocket().then();
return () => {
socket.current?.close();
};
}, []);
return (
<div>
在线人数 <span className='font-mono'>{count}</span>
</div>
);
};
export default OnlineCount;
"use client";
import React, { useEffect, useRef, useState } from 'react';
import Monitor from 'utils/monitor';
const OnlineCount = () => {
const [count, setCount] = useState(0);
const socket = useRef<WebSocket | null>(null); // 使用 null 初始化 ref
const userIdRef = useRef<string | null>(null); // 存储 userId,避免重新渲染时重新获取
useEffect(() => {
async function initSocket() {
if (!userIdRef.current) {
const monitor = new Monitor();
userIdRef.current = await monitor.getVisitor();
}
if (!socket.current) {
socket.current = new WebSocket(`ws://localhost:3000/v1/ws?userId=$userIdRef.current`);
socket.current.onmessage = (event) => {
const message = event.data;
setCount(message);
};
}
}
initSocket();
return () => {
if (socket.current) {
socket.current.close();
socket.current = null; // 清除连接引用,以便下次重新渲染时重新创建
}
};
}, []); // 空数组表示只在挂载和卸载时执行
return (
<div>
在线人数 <span className='font-mono'>{count}</span>
</div>
);
};
export default OnlineCount;