Skip to content

Commit aa5d83a

Browse files
dongmucatclaude
andcommitted
fix(room): auto-redirect to room when user already in room
- Add auto-redirect logic in HomePage when user.currentRoomId exists - Add error handling in RoomPage to clear stale room state - Ensure socket reconnection works after page refresh - Fix "您已在房间中,请先退出当前房间" error on refresh Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 3f07b4d commit aa5d83a

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

frontend/src/pages/home/index.tsx

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState } from 'react'
1+
import { useState, useEffect } from 'react'
22
import { useNavigate } from 'react-router'
33
import { motion, AnimatePresence } from 'framer-motion'
44
import { BookOpen } from 'lucide-react'
@@ -16,6 +16,13 @@ export default function HomePage() {
1616
const [localError, setLocalError] = useState('')
1717
const [showRules, setShowRules] = useState(false)
1818

19+
// 如果用户已在房间中,自动跳转到该房间
20+
useEffect(() => {
21+
if (user?.currentRoomId) {
22+
navigate(`/room/${user.currentRoomId}`, { replace: true })
23+
}
24+
}, [user?.currentRoomId, navigate])
25+
1926
const handleCreateRoom = async () => {
2027
setLocalError('')
2128
try {

frontend/src/pages/room/index.tsx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,20 @@ export default function RoomPage() {
132132
}
133133
}, [roomId, fetchRoomInfo])
134134

135+
// 如果房间不存在,清除用户状态并返回首页
136+
useEffect(() => {
137+
if (error && !isLoading && !room) {
138+
const user = useAuthStore.getState().user
139+
if (user?.currentRoomId === roomId) {
140+
useAuthStore.setState({
141+
user: { ...user, currentRoomId: null }
142+
})
143+
}
144+
toast('房间不存在或已关闭')
145+
navigate('/', { replace: true })
146+
}
147+
}, [error, isLoading, room, roomId, navigate])
148+
135149
useEffect(() => {
136150
if (roomId && token && !connectedRef.current) {
137151
connect(token, roomId)

0 commit comments

Comments
 (0)