Commit 803563af by weiw

fix:处理登录后无发刷新登录状态的 bug

parent 5725d3c7
// AuthContext.tsx
import type { ReactNode } from 'react'
import React, { createContext, useContext, useState } from 'react'
import React, { createContext, useContext, useEffect, useState } from 'react'
import { useLocalStorageState } from 'ahooks'
import { fetchLoginByUid } from '@/api/common'
import useToast from '@/hooks/useToast'
......@@ -28,6 +28,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
defaultValue: '',
},
)
const [isLoggedIn, setIsLoggedIn] = useState(!!token)
const [showLoginModal, setShowLoginModal] = useState(false)
const [showLoginTip, setShowLoginTip] = useState(!token)
......@@ -55,6 +56,32 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
setShowLoginTip(showLoginModal)
}
// 监听 localStorage 变化事件
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === '__TOKEN__') {
const newToken = e.newValue
setIsLoggedIn(!!newToken)
if (!newToken) {
setShowLoginTip(true)
}
}
}
window.addEventListener('storage', handleStorageChange)
return () => {
window.removeEventListener('storage', handleStorageChange)
}
}, [])
// 添加 effect 监听 token 变化
useEffect(() => {
setIsLoggedIn(!!token)
if (!token) {
setShowLoginTip(true)
}
}, [token])
return (
// eslint-disable-next-line react/no-unstable-context-value
<AuthContext.Provider value={{ isLoggedIn, showLoginTip, showLoginModal, login, logout, toggleLoginModal }}>
......
......@@ -51,10 +51,6 @@ export const Home: React.FC = () => {
const [token, setToken] = useLocalStorageState<string | undefined>('__TOKEN__', {
defaultValue: '',
})
const [, setIsLoggedIn] = useState(!!token)
const [, setShowLoginModal] = useState(false)
const [, setShowLoginTip] = useState(!token)
// 检查当前路径是否包含 "/chat/"
// const showOutlet = location.pathname.includes('/chat/')
// const handleCreateConversation = (question: string) => {
......@@ -127,14 +123,23 @@ export const Home: React.FC = () => {
const url = new URL(window.location.href)
// 获取查询参数
const searchParams = new URLSearchParams(url.search)
const token = searchParams.get('token')
const loginCode = searchParams.get('loginCode')
const res = await fetchLoginByToken(token)
const res = await fetchLoginByToken(loginCode)
// 模拟登录 可以用来测试
// const res = await fetchLoginByUid('123123')
if (res.data) {
setToken(res.data.token)
setIsLoggedIn(!!token)
setShowLoginTip(!token)
setShowLoginModal(false)
// 主动触发 storage 事件,确保其他组件能监听到变化
window.dispatchEvent(new StorageEvent('storage', {
key: '__TOKEN__',
oldValue: token,
newValue: res.data.token,
url: window.location.href,
storageArea: localStorage,
}))
await getQuestionList()
initConversation()
dispatch(fetchConversations())
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment