This commit is contained in:
mmc
2026-05-06 16:49:07 +08:00
parent 8413284b45
commit de1998a9a8
6 changed files with 135 additions and 52 deletions

View File

@@ -3,10 +3,12 @@ import { useDispatch } from 'react-redux';
// 👇 保留 import,但是把类型定义放到 store 后面
import userReducer from './userSlice';
import stationReducer from './stationSlice'; // 👈 加这个
export const store = configureStore({
reducer: {
user: userReducer,
station: stationReducer, // 👈 加这个
},
});

42
src/store/stationSlice.ts Normal file
View File

@@ -0,0 +1,42 @@
import { createSlice } from '@reduxjs/toolkit';
// 从 localStorage 加载上次选中的场站
const loadStationFromStorage = () => {
try {
const station = localStorage.getItem('currentStation');
return station ? JSON.parse(station) : null;
} catch {
return null;
}
};
const initialState = {
currentStation: loadStationFromStorage(), // 当前选中场站(完整对象)
stationId: loadStationFromStorage()?.id || null, // 方便直接用 id
};
const stationSlice = createSlice({
name: 'station',
initialState,
reducers: {
// 设置当前场站
setCurrentStation: (state, action) => {
state.currentStation = action.payload;
state.stationId = action.payload?.id || null;
localStorage.setItem('currentStation', JSON.stringify(action.payload));
},
// 清空场站(退出登录时用)
clearStation: (state) => {
state.currentStation = null;
state.stationId = null;
localStorage.removeItem('currentStation');
},
},
});
export const { setCurrentStation, clearStation } = stationSlice.actions;
export default stationSlice.reducer;
//使用const { currentStation, stationId } = useSelector((state: RootState) => state.station);