Commit 59926472 by HoMeTown

feat: 添加路由守卫

parent 30e06255
import React, { useEffect } from 'react'
import React from 'react'
import { useParams } from 'react-router-dom'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { setCurrentConversation } from '@/store/conversationSlice'
export const Chat: React.FC = () => {
const { id } = useParams<{ id: string }>()
const dispatch = useAppDispatch()
const { currentConversationId } = useAppSelector(state => state.conversation)
// const dispatch = useAppDispatch()
// const { currentConversationId } = useAppSelector(state => state.conversation)
useEffect(() => {
if (id && id !== currentConversationId) {
dispatch(setCurrentConversation(id))
// dispatch(fetchConversationDetails(id))
}
}, [id, currentConversationId, dispatch])
// useEffect(() => {
// if (id && id !== currentConversationId) {
// dispatch(setCurrentConversation(id))
// // dispatch(fetchConversationDetails(id))
// }
// }, [id, currentConversationId, dispatch])
return (
<h1>
聊天页面 - Chat ID:
......
......@@ -2,8 +2,9 @@ import React from 'react'
import { Route, Routes } from 'react-router-dom'
import { Home } from '../pages/Home'
import { Chat } from '../pages/Chat'
import { withRouteChangeHandler } from './RouteChangeHandler'
export const AppRoutes: React.FC = () => {
const AppRoutesComponent: React.FC = () => {
return (
<Routes>
<Route path="/" element={<Home />} />
......@@ -11,3 +12,5 @@ export const AppRoutes: React.FC = () => {
</Routes>
)
}
export const AppRoutes = withRouteChangeHandler(AppRoutesComponent)
import React, { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { clearCurrentConversation } from '@/store/conversationSlice'
import { useAppDispatch } from '@/store/hook'
export function withRouteChangeHandler(WrappedComponent: React.ComponentType) {
return (props: any) => {
const location = useLocation()
const dispatch = useAppDispatch()
useEffect(() => {
if (location.pathname === '/') {
dispatch(clearCurrentConversation())
}
// 这里可以添加其他路由相关的逻辑
}, [location, dispatch])
return <WrappedComponent {...props} />
}
}
......@@ -54,6 +54,9 @@ const conversationSlice = createSlice({
setCurrentConversation: (state, action: PayloadAction<string>) => {
state.currentConversationId = action.payload
},
clearCurrentConversation: (state) => {
state.currentConversationId = null
},
addConversation: (state, action: PayloadAction<Conversation>) => {
state.conversations.unshift(action.payload)
},
......@@ -97,6 +100,6 @@ const conversationSlice = createSlice({
},
})
export const { setCurrentConversation, clearNavigationFlag } = conversationSlice.actions
export const { setCurrentConversation, clearCurrentConversation, clearNavigationFlag } = conversationSlice.actions
export default conversationSlice.reducer
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