redux 加入

This commit is contained in:
mmc
2026-04-21 10:33:48 +08:00
parent fc23b6fa22
commit 79f8252b08
8 changed files with 138 additions and 68 deletions

10
src/store/index.js Normal file
View File

@@ -0,0 +1,10 @@
import { configureStore } from '@reduxjs/toolkit';
import userReducer from './userSlice';
export const store = configureStore({
reducer: {
user: userReducer,
},
});
export default store;

37
src/store/userSlice.js Normal file
View File

@@ -0,0 +1,37 @@
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
token: localStorage.getItem('token') || null,
userInfo: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null,
isAuthenticated: localStorage.getItem('isAuthenticated') === 'true',
};
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
// 登录
login: (state, action) => {
state.token = action.payload.token;
state.userInfo = action.payload.userInfo;
state.isAuthenticated = true;
localStorage.setItem('token', action.payload.token);
localStorage.setItem('user', JSON.stringify(action.payload.userInfo));
localStorage.setItem('isAuthenticated', 'true');
},
// 退出
logout: (state) => {
state.token = null;
state.userInfo = null;
state.isAuthenticated = false;
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem('isAuthenticated');
},
},
});
export const { login, logout } = userSlice.actions;
export default userSlice.reducer;