feat: 集成聊天插件并优化加载机制

前端改动:
- 在首页动态加载聊天插件,仅在首页展示
- 组件卸载时自动清理脚本和 DOM 元素,避免内存泄漏
- 登录、注册、退出登录时使用 window.location 强制刷新页面
- 确保聊天插件在登录后立即显示,退出后立即消失

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
yanlongqi 2025-11-10 15:15:53 +08:00
parent 41cf72db12
commit f79d1368b8
2 changed files with 36 additions and 4 deletions

View File

@ -175,6 +175,34 @@ const Home: React.FC = () => {
loadDailyRanking() loadDailyRanking()
}, []) }, [])
// 动态加载聊天插件(仅在首页加载)
useEffect(() => {
const script = document.createElement('script')
script.src = 'http://xiwang.nianliuxi.com:8282/chat/api/embed?protocol=http&host=xiwang.nianliuxi.com:8282&token=f131cc7227f4ee8e'
script.async = true
script.defer = true
script.id = 'chat-embed-script' // 添加 ID 以便于查找和清理
document.body.appendChild(script)
// 组件卸载时清理脚本和聊天插件元素
return () => {
// 移除脚本标签
const scriptElement = document.getElementById('chat-embed-script')
if (scriptElement) {
document.body.removeChild(scriptElement)
}
// 清理聊天插件可能创建的 DOM 元素
// 根据聊天插件的实际 DOM 结构调整选择器
const chatElements = document.querySelectorAll('[id*="chat"], [class*="chat"], [id*="embed"], [class*="embed"]')
chatElements.forEach(element => {
if (element.parentNode) {
element.parentNode.removeChild(element)
}
})
}
}, [])
// 处理用户类型更新 // 处理用户类型更新
const handleUpdateUserType = async (values: { user_type: string }) => { const handleUpdateUserType = async (values: { user_type: string }) => {
setLoading(true) setLoading(true)
@ -315,7 +343,8 @@ const Home: React.FC = () => {
localStorage.removeItem('user') localStorage.removeItem('user')
setUserInfo(null) setUserInfo(null)
message.success('已退出登录') message.success('已退出登录')
navigate('/login') // 跳转到登录页并强制刷新,确保清理聊天插件
window.location.href = '/login'
}, },
}) })
} }

View File

@ -60,7 +60,8 @@ const Login: React.FC = () => {
setUserTypeModalVisible(true) setUserTypeModalVisible(true)
} else { } else {
message.success('登录成功') message.success('登录成功')
navigate('/') // 使用 window.location 跳转,刷新页面以正确加载首页的聊天插件
window.location.href = '/'
} }
} else { } else {
message.error(data.message || '登录失败') message.error(data.message || '登录失败')
@ -90,7 +91,8 @@ const Login: React.FC = () => {
message.success('注册成功') message.success('注册成功')
setRegisterModalVisible(false) setRegisterModalVisible(false)
navigate('/') // 使用 window.location 跳转,刷新页面以正确加载首页的聊天插件
window.location.href = '/'
} else { } else {
message.error(data.message || '注册失败') message.error(data.message || '注册失败')
} }
@ -121,7 +123,8 @@ const Login: React.FC = () => {
message.success('身份类型设置成功') message.success('身份类型设置成功')
setUserTypeModalVisible(false) setUserTypeModalVisible(false)
navigate('/') // 使用 window.location 跳转,刷新页面以正确加载首页的聊天插件
window.location.href = '/'
} else { } else {
message.error(data.message || '更新失败') message.error(data.message || '更新失败')
} }