修改
This commit is contained in:
@@ -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
42
src/store/stationSlice.ts
Normal 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);
|
||||
|
||||
Reference in New Issue
Block a user