React中useEffect+Socket.io+Context API状态更新异常求助
问题分析
你当前的核心问题是:getAllFriends 是异步操作,调用后 friends 状态不会立即更新,但Socket连接和在线用户筛选逻辑没有等待friends加载完成,导致第一次筛选时friends为空。另外,现有筛选逻辑存在重复添加在线用户的问题,且依赖项设置不完整。
解决方案
1. 拆分Effect,确保数据加载完成后再初始化Socket
把验证授权、获取用户信息/好友列表的逻辑和Socket连接逻辑拆分,通过Promise.all等待异步数据加载完成后,再建立Socket连接:
useEffect(() => { let token = JSON.parse(localStorage.getItem("token")); if (!token) { setIsAuthenticated(false); navigate("/auth"); return; } setIsAuthenticated(true); // 并行获取用户信息和好友列表,完成后再初始化Socket Promise.all([getProfile(), getAllFriends()]) .then(() => { socket.current = io("http://localhost:3000", { query: { token } }); makeConnection(); }) .catch(() => { toast({ title: "数据加载失败", status: "error", duration: 3000, position: "bottom", }); localStorage.removeItem("token"); navigate("/auth"); setIsAuthenticated(false); }); return () => { if (socket.current) { socket.current.disconnect(); socket.current.off(); } }; }, []);
2. 优化在线用户筛选逻辑,避免重复添加
原来的setOnlineUsers是累加模式,会导致好友更新时重复添加在线用户。改成每次根据friends和localOnline重新计算在线好友列表:
useEffect(() => { if (friends.length === 0 || localOnline.length === 0) return; // 筛选出在线的好友ID const onlineFriendIds = friends .map(fr => fr.friend_id) .filter(friendId => localOnline.includes(friendId)); // 直接替换在线用户列表,避免重复 setOnlineUsers(onlineFriendIds); }, [friends, localOnline, setOnlineUsers]);
3. 修正Socket事件监听逻辑
在Socket连接成功后,主动请求一次在线用户列表,确保能拿到最新的在线状态:
function makeConnection() { socket.current.on("connect", () => { console.log("Connected"); // 主动触发获取在线用户列表的请求 socket.current.emit("check-active-users"); }); socket.current.on("update-active-users", (arr) => { setLocalOnline(arr); }); // 其他事件监听保持不变... }
4. 修正清理函数
移除无效的disconnect事件监听,同时清理所有Socket事件避免内存泄漏:
return () => { if (socket.current) { socket.current.disconnect(); socket.current.off(); } };
完整修改后的代码
import { useToast } from "@chakra-ui/toast"; import React, { lazy, Suspense, useContext, useEffect, useState } from "react"; import { Outlet, useNavigate } from "react-router-dom"; import { io } from "socket.io-client"; import Loader from "../components/Loader"; import { Context } from "../context/StateProvider"; const Home = () => { const SideBar = lazy(() => import("../components/SideBar")); const BG = lazy(() => import("../components/BG")); const toast = useToast(); const { setIsAuthenticated, friends, getAllFriends, getProfile, setOnlineUsers, socket, } = useContext(Context); const navigate = useNavigate(); const [localOnline, setLocalOnline] = useState([]); useEffect(() => { let token = JSON.parse(localStorage.getItem("token")); if (!token) { setIsAuthenticated(false); navigate("/auth"); return; } setIsAuthenticated(true); Promise.all([getProfile(), getAllFriends()]) .then(() => { socket.current = io("http://localhost:3000", { query: { token } }); makeConnection(); }) .catch(() => { toast({ title: "数据加载失败", status: "error", duration: 3000, position: "bottom", }); localStorage.removeItem("token"); navigate("/auth"); setIsAuthenticated(false); }); return () => { if (socket.current) { socket.current.disconnect(); socket.current.off(); } }; }, []); function makeConnection() { socket.current.on("connect", () => { console.log("Connected"); socket.current.emit("check-active-users"); }); socket.current.on("update-active-users", (arr) => { setLocalOnline(arr); }); socket.current.on("join-room", (roomID) => { toast({ title: "开始和好友聊天吧", status: "info", duration: 2000, position: "bottom", }); }); socket.current.on("error", (error) => { toast({ title: error.name, position: "bottom", status: "error", duration: 3000, isClosable: true, description: error.message, }); if (error.name === "JsonWebTokenError" || error.name === "TokenExpiredError") { localStorage.removeItem("token"); navigate("/auth"); setIsAuthenticated(false); } }); } useEffect(() => { if (friends.length === 0 || localOnline.length === 0) return; const onlineFriendIds = friends .map(fr => fr.friend_id) .filter(id => localOnline.includes(id)); setOnlineUsers(onlineFriendIds); }, [friends, localOnline, setOnlineUsers]); return ( <div className="h-screen w-screen"> <div className="flex h-full w-full"> <Suspense fallback={<Loader />}> <SideBar /> </Suspense> <div className=" h-full w-full bg-[#1F1F22]"> <div className=" absolute h-full overflow-hidden w-full"> <Suspense fallback={<Loader />}> <BG /> </Suspense> </div> <Outlet /> </div> </div> </div> ); }; export default React.memo(Home);
内容的提问来源于stack exchange,提问作者MR. WOLF
相关产品推荐
相关产品推荐

