1.reducers(user.js)
// 依赖
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
// 一些api方法
import { fetchLogin, fetchUserInfo } from '../../api';
// 可共享的子store可共享数据
const initialState:any = {
token: localStorage.getItem('token'),
userInfo: {},
roleInfo:{},
menulist:[]
}
// 一些异步方法
export const login = createAsyncThunk(
'user/login',
async (data: any) => {
const res:any = await fetchLogin(data);
// The value we return becomes the `fulfilled` action payload
return res;
}
);
export const getInfo = createAsyncThunk(
'user/info',
async () => {
const res:any = await fetchUserInfo();
console.log(res);
// The value we return becomes the `fulfilled` action payload
return res;
}
);
const toTree = (arr:any)=>{
// 父级
let p = arr.filter((ele:any)=>!ele.pid)
// 子级
p.map((ele:any,idx:any)=>{
p[idx]['children'] = arr.filter((ele1:any)=>ele1.pid === ele._id)
})
console.log(p);
return p
}
export const user = createSlice({
name: 'user',
initialState,
// “reducers”字段允许我们定义reducers并生成相关的操作
// The `reducers` field lets us define reducers and generate associated actions
// 同步的方法
reducers: {
logout: (state) => {
localStorage.removeItem('token')
state.token = null
state.userInfo = {}
state.roleInfo = {}
}
},
// 异步方法的回调
extraReducers: (builder) => {
builder
.addCase(login.fulfilled, (state, action) => {
state.token = action.payload.token
localStorage.setItem('token',action.payload.token)
})
.addCase(getInfo.fulfilled, (state, action) => {
console.log(action.payload);
if(action.payload.userInfo){
state.userInfo = action.payload.userInfo
state.roleInfo = action.payload.roleInfo
state.menulist = toTree(action.payload.menulist)
}
})
},
});
export const { logout } = user.actions;
export default user.reducer;
2.index.js
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import logger from 'redux-logger';
import counter from '@/store/reducers/counter';
import user from '@/store/reducers/user'
import article from '@/store/reducers/article'
export const store = configureStore({
// 子store
reducer: {
counter,
user,
article
},
// 安装中间件 需要考虑原有的中间件 使用concat 链接
middleware: (getDefaultMiddlewares)=>(getDefaultMiddlewares().concat(logger))
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>;
js