老师您好:按您的教程 Redux ToolKit写完了,然后报错了
来源:10-8 【redux-toolkit】sotre配置(configureStore)与异步处理(createAsyncThunk)

慕村5307545
2024-07-03
store.ts
// import { createStore, applyMiddleware } from 'redux';
import { myMenusSlice} from './menuSlice';
import {combineReducers, configureStore} from '@reduxjs/toolkit'
const rootReducer = combineReducers({
myMenus: myMenusSlice
})
// const store = createStore(rootReducer);
const store = configureStore({
reducer: rootReducer,
// middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(actionLog)
devTools: true //chrome extensions: Redux DevTools
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export default store;
menuSlice.ts
import axios from 'axios';
import {api} from '../common/api';
import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
export interface MenuType {
id? : number | string,
icon? : string,
name? : string,
path? : string,
children? : MenuType[]
type? : number,
[key: string] : any
// parentId? : number,
// sort? : number,
// query? : string,
// status? : number,
}
export interface MenusType {
menus: MenuType[],
loading: boolean,
error: string | null,
}
const defaultState : MenusType = {
loading: true,
error: null,
menus: [ {
id: '1',
icon: 'icon-dashboard',
name: "主面板",
path: '/sys/overview',
},
{
id: '2',
icon: 'icon-user',
name: "用户管理",
path: '/sys/user',
},
{
id: '3',
icon: 'icon-menu-s',
name: "菜单管理",
path: '/sys/menu',
},]
}
export const currMenus = createAsyncThunk(
"menu/myMenus",
async (arg, thunkApi) => {
thunkApi.dispatch(myMenusSlice.actions.fetchStart())
try{
const {data} = await axios.get(api.menu.curr);
if(data.status){
thunkApi.dispatch(myMenusSlice.actions.fetchSuccess(data.data))
}else{
thunkApi.dispatch(myMenusSlice.actions.fetchFail(data.msg))
}
}catch(error){
thunkApi.dispatch(myMenusSlice.actions.fetchFail(error));
}
}
);
export const myMenusSlice = createSlice({
name: "myMenus",
initialState: defaultState,
reducers: {
fetchStart: (state) => {
state.loading = true;
},
fetchSuccess: (state, action) => {
state.loading = false;
state.menus = action.payload;
},
// fetchFail: (state, action: PayloadAction<string | null>) => {
// state.error = action.payload;
// state.loading = false;
// }
fetchFail: (state, action) => {
state.error = action.payload;
state.loading = false;
}
}
});
调用的地方:
const menus = useSelector(state => {
console.log(state);
return state.myMenus.menus;
});
这里打印出来是空的,然后报错如下:
然后一脸懵,不知道是什么问题?
写回答
1回答
-
阿莱克斯刘
2024-07-06
Hi 同学,请注意一下单词拼写,有的地方你使用的是复数menus,有些地方使用的却是单数形式menu,我怀疑是单词拼写的问题。
012024-07-09
相似问题
加入中间件后类型报错了 (已解决)
回答 1
老师我dispatch报类型错误
回答 5